package com.info.zhiduoduo.admin.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.info.zhiduoduo.admin.listener.CrowdsourceProjectUploadListener;
import com.info.zhiduoduo.admin.listener.UploadCrowdsourceListener;
import com.info.zhiduoduo.admin.listener.UploadDealCrowdsourceProjectListener;
import com.info.zhiduoduo.admin.model.dto.common.BatchManualErrorDto;
import com.info.zhiduoduo.admin.model.dto.kingdee.ExportReceivableDto;
import com.info.zhiduoduo.admin.model.formbean.account.RepayCrowdsourceProjectItemFormBean;
import com.info.zhiduoduo.admin.model.formbean.common.BatchManualErrorFormBean;
import com.info.zhiduoduo.admin.model.formbean.common.CrowdsourceBatchManualErrorFormBean;
import com.info.zhiduoduo.admin.model.formbean.crowdsource.*;
import com.info.zhiduoduo.admin.model.formbean.invoice.EditContractorInvoiceFormBean;
import com.info.zhiduoduo.admin.model.formbean.invoice.QueryContractorInvoiceFormBean;
import com.info.zhiduoduo.admin.model.formbean.project.GenerateProjectAcceptance;
import com.info.zhiduoduo.common.baidusdk.BankcardService;
import com.info.zhiduoduo.common.baidusdk.domain.BankcardResponse;
import com.info.zhiduoduo.common.configs.*;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.company.CompanyAccountFlowBizType;
import com.info.zhiduoduo.common.constants.company.CompanyPayType;
import com.info.zhiduoduo.common.constants.crowdsource.CrowdsourceProjectMatchState;
import com.info.zhiduoduo.common.constants.crowdsource.CrowdsourceProjectType;
import com.info.zhiduoduo.common.constants.crowdsource.CrowdsourceRegfromType;
import com.info.zhiduoduo.common.constants.crowdsource.CrowdsourceUserType;
import com.info.zhiduoduo.common.constants.maker.MakerType;
import com.info.zhiduoduo.common.constants.partner.PartnerBrokerageState;
import com.info.zhiduoduo.common.constants.partner.PartnerBrokerageType;
import com.info.zhiduoduo.common.constants.pay.PayTypeSn;
import com.info.zhiduoduo.common.constants.project.CalcAmountType;
import com.info.zhiduoduo.common.constants.project.ProjectType;
import com.info.zhiduoduo.common.excelconverter.ZddReadListener;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.exception.SmartException;
import com.info.zhiduoduo.common.formbean.BaseListFormBean;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.Base64;
import com.info.zhiduoduo.common.utils.*;
import com.info.zhiduoduo.common.utils.poi.DocUtils;
import com.info.zhiduoduo.core.service.*;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.core.service.common.DocService;
import com.info.zhiduoduo.core.service.common.ProjectFileService;
import com.info.zhiduoduo.repository.dto.account.ReceiptDto;
import com.info.zhiduoduo.repository.dto.account.ReceivableDto;
import com.info.zhiduoduo.repository.dto.company.CompanyDetailDto;
import com.info.zhiduoduo.repository.dto.company.RechargeReceiptDto;
import com.info.zhiduoduo.repository.dto.crowdsource.*;
import com.info.zhiduoduo.repository.dto.maker.MakerDetailDto;
import com.info.zhiduoduo.repository.dto.maker.StudioDetailDto;
import com.info.zhiduoduo.repository.entity.company.*;
import com.info.zhiduoduo.repository.entity.crowdsource.*;
import com.info.zhiduoduo.repository.entity.foreign.ForeignInvoice;
import com.info.zhiduoduo.repository.entity.invoice.Invoice;
import com.info.zhiduoduo.repository.entity.maker.MakerAccount;
import com.info.zhiduoduo.repository.entity.maker.MakerBankcard;
import com.info.zhiduoduo.repository.entity.maker.MakerStudio;
import com.info.zhiduoduo.repository.entity.partner.PartnerAccountflow;
import com.info.zhiduoduo.repository.entity.partner.PartnerBrokerage;
import com.info.zhiduoduo.repository.entity.pay.Payment;
import com.info.zhiduoduo.repository.entity.quota.CrowdsourceCityQuota;
import com.info.zhiduoduo.repository.entity.system.SystemManager;
import com.info.zhiduoduo.repository.mapper.company.CompanyMapper;
import com.info.zhiduoduo.repository.mapper.company.CompanyPaymentMapper;
import com.info.zhiduoduo.repository.mapper.company.CompanyRechargeMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.*;
import com.info.zhiduoduo.repository.mapper.maker.MakerAccountMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerStudioMapper;
import com.info.zhiduoduo.repository.mapper.system.TaxSourceMapper;
import com.info.zhiduoduo.repository.util.LimitPromptUtil;
import com.info.zhiduoduo.wxsdk.utils.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CrowdsourceService extends BaseService {

	@Resource
	DocService docService;
	@Autowired
	CoreProjectService coreProjectService;
	@Autowired
	CrowdsourceProjectService crowdsourceProjectService;
	@Autowired
	CoreBrokerageService coreBrokerageService;
	@Autowired
	CoreCompanyService coreCompanyService;
	@Autowired
	CoreInvoiceService coreInvoiceService;
	@Autowired
	BankcardService bankcardService;
	@Autowired
	PartnerCrowdsourceCostService partnerCrowdsourceCostService;

	@Resource
	CrowdsourceMapper crowdsourceMapper;
	@Resource
	CrowdsourceAccountMapper crowdsourceAccountMapper;
	@Resource
	CrowdsourceTradeRecordMapper crowdsourceTradeRecordMapper;
	@Resource
	CrowdsourceProjectMapper crowdsourceProjectMapper;
	@Resource
	CrowdsourceProjectItemMapper crowdsourceProjectItemMapper;
	@Resource
	CrowdsourcePayConfigMapper crowdsourcePayConfigMapper;
	@Resource
	CommonService commonService;
	@Resource
	CrowdsourceTradeRecordItemMapper crowdsourceTradeRecordItemMapper;
	@Resource
	CoreCrowdsourceService coreCrowdsourceService;
	@Resource
	CompanyMapper companyMapper;
	@Resource
	MakerStudioMapper makerStudioMapper;
	@Resource
	CrowdsourceFileMapper crowdsourceFileMapper;
	@Resource
	CrowdsourceProjectMatchMapper crowdsourceProjectMatchMapper;
	@Resource
	CompanyRechargeMapper companyRechargeMapper;
	@Resource
	TaxPaymentVoucherMapper taxPaymentVoucherMapper;
	@Resource
	TaxSourceMapper taxSourceMapper;
	@Resource
	ProjectFileService projectFileService;
	@Resource
	MakerAccountMapper makerAccountMapper;
	@Resource
	CoreSensitiveService coreSensitiveService;
	@Resource
	MakerMapper makerMapper;
	@Resource
	CompanyPaymentMapper companyPaymentMapper;
	@Resource
	ContractorInvoiceMapper contractorInvoiceMapper;
	@Resource
	NotificationConfig notificationConfig;

	@Resource
	ZddUrlConfig zddUrlConfig;
	@Resource
	YunKongConfig yunKongConfig;
	@Resource
	UploadPathConfig uploadPathConfig;
	@Autowired
	DocConfig docConfig;
	@Resource
	KingdeeTemplateConfig kingdeeTemplateConfig;
	@Resource
	CrowdsourceImportRecordMapper crowdsourceImportRecordMapper;

	public SmartResult editRealnameInfo(BaseSimpleFormBean<CrowdsourceRealNameAuthFormBean> formBean) {
		CrowdsourceRealNameAuthFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();
		if (reqdata.getBindcompid() == 0 || StringUtil.isAnyEmpty(reqdata.getAcctno(), reqdata.getRealname(), reqdata.getIdno()))
			return errorParamSmartResult();

		int compid = reqdata.getBindcompid();
		if (compid == 0) return errorParamSmartResult();
		Company company = new Company().selectById(compid);
		CrowdsourseRealNameDto crowdsourseRealNameDto = new CrowdsourseRealNameDto();
		CrowdsourceAccount crowdsourceAccount = new CrowdsourceAccount().selectOne(
				Condition.create().eq("crowdsourceid", reqdata.getCrowdsourceid()));
		//是否修改了银行卡号
		if (!crowdsourceAccount.getAcctno().equals(reqdata.getAcctno())) {
			//如果存在共青城自然人编号
			if (StringUtil.isNotEmpty(crowdsourceAccount.getNaturalNumber())) {
				//在共青城那边修改保存银行信息
				SmartResult resultBank = saveBank(crowdsourceAccount.getNaturalNumber(), reqdata.getAcctno());
				if (resultBank != null && resultBank.getState() == StatusMsg.StatusMsg_100.getState()) {
					String yunKongId = resultBank.getObject().toString();
					crowdsourceAccount.setAcctno(reqdata.getAcctno()).setYunkongId(yunKongId).setYunkongAcctno(reqdata.getAcctno());
				} else {
					return resultBank;
				}
			} else {
				crowdsourceAccount.setAcctno(reqdata.getAcctno());
			}
			// 获取银行卡省份城市
			BankcardResponse.DataDTO bankcardInfo = bankcardService.getBankcardInfo(reqdata.getAcctno());
			if (bankcardInfo != null) {
				crowdsourceAccount.setCardName(bankcardInfo.getCardName())
						.setBankProvince(bankcardInfo.getProvince())
						.setBankCity(bankcardInfo.getCity());
			}
		}
		//保存自然人身份证图片
		if (StringUtil.isNotEmpty(reqdata.getIdfrontimg())) {
			saveCrowdsourceFile(reqdata.getCrowdsourceid(), reqdata.getIdfrontimg(), 1);
		}
		if (StringUtil.isNotEmpty(reqdata.getIdbackimg())) {
			saveCrowdsourceFile(reqdata.getCrowdsourceid(), reqdata.getIdbackimg(), 2);
		}
		crowdsourceAccount.setRealname(reqdata.getRealname())
				.setIdentityType(reqdata.getIdentityType())
				.setIdno(reqdata.getIdno())
				.setAcctphone(reqdata.getAcctphone())
				.setBankname(reqdata.getBankname())
				.setBindcompid(reqdata.getBindcompid())
				.setTags(reqdata.getTags())
				.setProvince(StringUtil.toInt(reqdata.getProvince()))
				.setCity(StringUtil.toInt(reqdata.getCity()));
		boolean b = crowdsourceAccount.update(Condition.create().eq("crowdsourceid", reqdata.getCrowdsourceid()));
		crowdsourseRealNameDto.setCrowdsourceid(reqdata.getCrowdsourceid());
		return smartResult(crowdsourseRealNameDto);
	}

	private void saveCrowdsourceFile(int userid, String path, int type) {
		crowdsourceFileMapper.delFileByIdAndType(userid, type);
		CrowdsourceFile crowdsourceFile = new CrowdsourceFile();
		crowdsourceFile.setFilePath(path);
		crowdsourceFile.setCrowdsourceid(userid);
		crowdsourceFile.setFileType(type);
		crowdsourceFile.insert();
	}

	/**
	 * 众包自然人实名认证
	 *
	 * @param formBean
	 * @return
	 */

	public SmartResult realNameConfirm(BaseSimpleFormBean<CrowdsourceRealNameFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata().getCrowdsourceid()) {
			return errorParamSmartResult();
		}
		CrowdsourceRealNameFormBean reqdata = formBean.getReqdata();
		if (StringUtil.isAnyEmpty(reqdata.getHUITIPLATSRL(), reqdata.getSFGHOCRPLATSRL(), reqdata.getSFRZDBLATSRL(),
				reqdata.getSFZMOCRPLATSRL())) {
			return errorParamSmartResult();
		}
		CrowdsourceAccount crowdsourceAccount = new CrowdsourceAccount().selectOne(
				Condition.create().eq("crowdsourceid", reqdata.getCrowdsourceid()));
		if (null == crowdsourceAccount) {
			return smartResult(StatusMsg.StatusMsg_602);
		}
		Crowdsource crowdsource = new Crowdsource().selectById(reqdata.getCrowdsourceid());
		if (null == crowdsource) {
			return smartResult(StatusMsg.StatusMsg_601);
		}
		crowdsourceAccount.setRealnameAuth(Constants.crowdsource_auth_3);
		if (!crowdsourceAccount.updateById()) {
			return smartResult(StatusMsg.StatusMsg_199);
		}
		return smartResult();
	}

	public SmartResult getCrowsourceList(BaseSimpleFormBean<CrowdsourceListFormBean> formBean) {
		CrowdsourceListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		Integer realnameAuth = reqdata.getRealnameAuth();
		if (realnameAuth == null) {
			realnameAuth = 3;
		}
		Integer registerCondition = reqdata.getRegisterCondition();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<CrowdsourceInfoDto> crowdsourceInfoDtos = crowdsourceAccountMapper.getList(reqdata.getName(), reqdata.getCompname(),
				realnameAuth, registerCondition);
		return smartResult(crowdsourceInfoDtos, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public SmartResult unbindcompany(BaseSimpleFormBean<Integer> formBean) {
		Integer crowdsourceid = formBean.getReqdata();
		boolean update = new CrowdsourceAccount().setBindcompid(0)
				.setRealnameAuth(Constants.crowdsource_auth_4)
				.update(Condition.create().eq("crowdsourceid", crowdsourceid));

		if (update) return smartResult();
		else return optFailSmartResult();
	}

	public SmartResult acceptProtocolAndAuth(BaseSimpleFormBean<Integer> formBean) {
		Integer id = formBean.getReqdata();
		CrowdsourceAccount crowdsourceAccount = new CrowdsourceAccount().selectOne(Condition.create().eq("crowdsourceid", id));
		if (crowdsourceAccount == null) return smartResult(StatusMsg.StatusMsg_601);

		if (crowdsourceAccount.getRealnameAuth() == Constants.crowdsource_auth_3) {
			return smartResult(StatusMsg.StatusMsg_603);
		}

		boolean update = crowdsourceAccount.setContractNo(genContractNo()).setRealnameAuth(Constants.crowdsource_auth_3).updateById();

		if (update) return smartResult();
		else return optFailSmartResult();
	}

	public SmartResult<CrowdsourceProjectBriefDto> getProjectList(BaseSimpleFormBean<CrowdsourceProjectListFormBean> formBean) {

		CrowdsourceProjectListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		//获取当前操作人
		SystemManager systemManager = new SystemManager().selectOne(Condition.create().eq("managerid", formBean.getUserid()));
		if (systemManager == null) return optFailSmartResult();

		String name = reqdata.getName();
		int state = reqdata.getState();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		int projectType = reqdata.getProjectType();
		int workType = reqdata.getWorkType();
		//1 已上传证据链  2  未上传证据链
		int whetherUploadFile = reqdata.getWhetherUploadFile();
		String strUploadFile = "";
		if (1 == whetherUploadFile) {
			strUploadFile = " and (csp.project_file_url is not null or csp.delivery_path is not null) ";
		} else if (2 == whetherUploadFile) {
			strUploadFile = " and (csp.project_file_url is null and csp.delivery_path is null) ";
		}
		int whetherSupplement = reqdata.getWhetherSupplement();
		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		Page<CrowdsourceProjectBriefDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());

		crowdsourceProjectMapper.listEffectiveProject(name, projectType, state, startDate, endDate, strUploadFile, whetherSupplement, reqdata.getCreateType(),systemManager.getManagerid(),systemManager.getRoleid(),reqdata.getPartyId(),reqdata.getFilterUserType(),workType);
		for (CrowdsourceProjectBriefDto dto : page) {
			if (null != dto && null != dto.getActualSender() && 0 != dto.getActualSender()) {
				Company company = new Company().selectById(dto.getActualSender());
				if (null != company) {
					dto.setActualCompanyName(company.getCompname());
				}
			}
		}
		return smartResultPage(page);
	}

	public SmartResult getProjectDetail(BaseSimpleFormBean<Integer> formBean) {

		Integer projectid = formBean.getReqdata();

		CrowdsourceProjectDetailDto detail = crowdsourceProjectMapper.getDetail(projectid);
		if (detail != null) {
			detail.setItemList(crowdsourceProjectItemMapper.getItemList(projectid));
		}
		return smartResult(detail);
	}

	/**
	 * 导出众包项目详情
	 *
	 * @param response  response
	 * @param projectid 项目id
	 */
	public void exportProjectDetail(HttpServletResponse response, int projectid) {

		List<CrowdsourceProjectItemDto> list = crowdsourceProjectItemMapper.getItemList(projectid);
		String file = RandomUtil.createRandomNo("众包项目详情", "");
		try {
			EasyExcel.write(getExcelOutPutStream(response, file), CrowdsourceProjectItemDto.class).sheet("众包项目详情").doWrite(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导出众包项目交易详情
	 *
	 * @param response response
	 * @param reqdata  reqdata
	 */
	public void exportProjectTransactionDetail(HttpServletResponse response, ExportProjectTransactionDetailFormBean reqdata) {
		String name = reqdata.getName();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		if (startDate == null) {
			startDate = new Date(0);
		}
		if (endDate == null) {
			endDate = new Date();
		}
		List<ExportProjectTransactionDetailDto> list = crowdsourceTradeRecordItemMapper.exportProjectTransactionDetail(name, startDate,
				endDate, "", 0,0);
		String file = RandomUtil.createRandomNo("众包项目交易详情", "");
		try {
			if (1 == reqdata.getAuth()) {
				EasyExcel.write(getExcelOutPutStream(response, file), ExportProjectTransactionDetailDto.class).sheet("众包项目交易详情").doWrite(list);
			}else {
				EasyExcel.write(getExcelOutPutStream(response, file), ExportProjectTransactionDetailsDto.class).sheet("众包项目交易详情").doWrite(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SmartResult getTradeRecordList(BaseSimpleFormBean<CrowdsourceTradeRecordListFormBean> formBean) {
		CrowdsourceTradeRecordListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		String name = reqdata.getName();
		Integer state = reqdata.getState();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();

		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		crowdsourceTradeRecordMapper.getTradeRecordList(name, state, startDate, endDate).forEach(dto -> {
			Integer projectid = dto.getProjectid();
			dto.setCrowdsourceNames(crowdsourceProjectItemMapper.getItemCrowdsourceNames(projectid));
			CrowdsourceCompanyParty party = new CrowdsourceCompanyParty().selectById(dto.getPartyId());
			if (null != party) {
				dto.setTransactionSubject(party.getCompanyName());
			}
			if (null != dto.getActualSender() && 0 != dto.getActualSender()) {
				Company company = new Company().selectById(dto.getActualSender());
				if (null != company) {
					dto.setActualCompanyName(company.getCompname());
				}
			}
		});

		return smartResultPage(page);
	}

	public SmartResult getTradeRecordItemList(BaseSimpleFormBean<CrowdsourceTradeRecordItemListFormBean> formBean) {

		CrowdsourceTradeRecordItemListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int projectid = reqdata.getProjectid();
		Integer status = reqdata.getStatus();

		List<CrowdsourceTradeRecordItemDto> list = crowdsourceTradeRecordItemMapper.getList(projectid, status);
		list.forEach(dto -> {
			//是招商或者平安银行支付
			Boolean isZsOrPa = false;
			if(dto.getPayId() != 0){
				Payment payment = new Payment().selectById(dto.getPayId());
				if(payment != null){
					isZsOrPa = PayTypeSn.ZS.equals(payment.getPayTypeSn()) || PayTypeSn.PA.equals(payment.getPayTypeSn());
				}
			}
			//只对交易中的计算
			if (1 == dto.getStatus() && isZsOrPa) {
				//获取交易时间
				Date transactionTime = dto.getTradetime();
				long differTime = DateUtil.differMinute(DateUtil.DateToStr("yyyy-MM-dd HH:mm:ss", transactionTime),
						DateUtil.DateToStr("yyyy-MM-dd HH:mm:ss", new Date()));
				if (120 < differTime) {
					dto.setWhetherOvertime(2);
				} else {
					dto.setWhetherOvertime(1);
				}
			}
		});
		return smartResult(list);
	}

	public SmartResult batchManualError(BaseSimpleFormBean<CrowdsourceBatchManualErrorFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata().getProjectId() ||
				formBean.getReqdata().getFormBeanList().size() <= 0) {
			return errorParamSmartResult();
		}
		CrowdsourceProject project = new CrowdsourceProject().selectById(formBean.getReqdata().getProjectId());
		if (null == project) {
			return smartResult(StatusMsg.StatusMsg_606);
		}
		CrowdsourceTradeRecord tradeRecord = new CrowdsourceTradeRecord().selectOne(
				Condition.create().eq("projectid", project.getProjectid()));
		if (null == tradeRecord) {
			return smartResult(StatusMsg.StatusMsg_610);
		}
		List<BatchManualErrorFormBean> formBeanList = formBean.getReqdata().getFormBeanList();
		List<BatchManualErrorDto> dtoList = new ArrayList<>();
		formBeanList.forEach(bean -> {
			CrowdsourceTradeRecordItem item = new CrowdsourceTradeRecordItem().selectById(bean.getTradeid());
			if (null == item) {
				BatchManualErrorDto dto = new BatchManualErrorDto();
				dto.setTradeid(bean.getTradeid()).setReason(StatusMsg.StatusMsg_444.getMsg());
				dtoList.add(dto);
				return;
			}
			if (!item.getBatchId().equals(tradeRecord.getBatchId())) {
				BatchManualErrorDto dto = new BatchManualErrorDto();
				dto.setTradeid(bean.getTradeid()).setReason("数据不一致");
				dtoList.add(dto);
				return;
			}
			if (Constants.CROWDSOURCE_BATCH_ITEM_PAYING == item.getStatus()) {
				item.setStatus(Constants.CROWDSOURCE_BATCH_ITEM_FAILED).setErrorMsg("人工处理：" + bean.getReason()).setFinishtime(new Date());
				if (!item.updateById()) {
					BatchManualErrorDto dto = new BatchManualErrorDto();
					dto.setTradeid(bean.getTradeid()).setReason(StatusMsg.StatusMsg_199.getMsg());
					dtoList.add(dto);
				}
			} else {
				BatchManualErrorDto dto = new BatchManualErrorDto();
				dto.setTradeid(bean.getTradeid()).setReason(StatusMsg.StatusMsg_448.getMsg());
				dtoList.add(dto);
			}
		});
		// 刷新整个总包项目的状态
		refreshCrowdsourceProjectState(tradeRecord, project);
		refreshCrowdsourceTradeRecordStatus(tradeRecord, project);
		tradeRecord.updateById();
		project.updateById();
		return smartResult(dtoList);
	}

	@Transactional
	public SmartResult repayProjectItem(BaseSimpleFormBean<RepayCrowdsourceProjectItemFormBean> formBean) {
		RepayCrowdsourceProjectItemFormBean reqdata = formBean.getReqdata();
		return crowdsourceProjectService.repayCrowdsourceProjectItem(reqdata.getItemid());
	}

	public SmartResult delCrowdsource(BaseSimpleFormBean<Integer> formBean) {
		@Valid Integer crowdsourceid = formBean.getReqdata();
		List<CrowdsourceProjectItemDto> list = crowdsourceProjectItemMapper.getItemListByUserid(crowdsourceid,
				CrowdsourceUserType.NATURAL_PERSON);
		if (!CollectionUtils.isEmpty(list)) {
			return smartResult(StatusMsg.StatusMsg_615);
		}

		crowdsourceMapper.delCrowdsource(crowdsourceid);
		return smartResult();
	}

	public SmartResult importCrowdsources(MultipartFile file) {
		if (!file.isEmpty()) {
			try {
				EasyExcel.read(file.getInputStream(), new ZddReadListener<Map<Integer, String>>() {
					@Override
					public void onException(Exception exception, AnalysisContext context) throws Exception {
						System.out.println(ExceptionUtil.getErrorStackTrace(exception));
					}

					@Override
					public void invoke(Map<Integer, String> map, AnalysisContext context) {
						if (map == null || StringUtil.isEmpty(map.get(0))) return;

						try {
							ImportCrowdsourceFormBean bean = new ImportCrowdsourceFormBean().setRealname(map.get(0))
									.setSex(StringUtil.toInt(map.get(1)))
									.setPhone(map.get(2))
									.setIdentityType(StringUtil.toInt(map.get(3)))
									.setIdno(map.get(4))
									.setAcctno(map.get(5))
									// .setAcctphone(map.get(6))
									.setBankname(map.get(6));

							Crowdsource crowdsource = new Crowdsource().setPhone(bean.getPhone())
									.setRegfrom(CrowdsourceRegfromType.COMPANY_ADD)
									.setNickname(bean.getRealname())
									.setSex(bean.getSex())
									.setState(Constants.crowdsource_state_2);
							if (!crowdsource.insert()) return;

							new CrowdsourceAccount().setCrowdsourceid(crowdsource.getCrowdsourceid())
									.setRealnameAuth(Constants.crowdsource_auth_3)
									.setRealname(bean.getRealname())
									.setIdno(bean.getIdno())
									.setAcctno(bean.getAcctno())
									.setAcctphone(bean.getPhone())
									.setBankname(bean.getBankname())
									.setIdentityType(bean.getIdentityType())
									.setContractNo(genContractNo())
									.insert();
						} catch (Exception e) {
							LogUtil.info("读取众包自然人报错：" + JSON.toJSONString(map));
						}
					}

					@Override
					public void doAfterAllAnalysed(AnalysisContext context) {

					}
				}).sheet().doRead();
				return smartResult();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return optFailSmartResult();
	}

	private String genContractNo() {
		return RandomUtil.createRandomNo("CROWD_", "");
	}

	/**
	 * 导入历史成交的众包项目
	 * @return
	 */
	@Transactional
	public SmartResult importDealedCrowdsourceProject(MultipartFile file, ImportDealCrowdsourceFormBean bean) {
		//选智零工的时候，需要选择：渠道、填写税源地
		if (bean.getWorkType() == Constants.WORK_TYPE_2 && (bean.getChannel() == null || bean.getTaxSourceId() == null)) {
			return smartResult(StatusMsg.StatusMsg_651);
		}
		if (bean.getPayId() == 0) {
			return smartResult(StatusMsg.StatusMsg_330);
		}
		if (file == null || file.isEmpty()) {
			return smartResult(StatusMsg.StatusMsg_134);
		}

		try {
			//读取文件
			UploadDealCrowdsourceProjectListener listener = new UploadDealCrowdsourceProjectListener(bean, makerStudioMapper, companyMapper,
					coreInvoiceService, coreBrokerageService, coreCrowdsourceService, coreCompanyService);
			EasyExcel.read(file.getInputStream(), ImportDealCrowdsourceProjectFormBean.class, listener).sheet().doRead();
			return listener.getSmartResult();
		} catch (Exception e) {
			log.error("导入已成交的智众包项目失败", e);
			//手动回滚
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return SmartResult.fail(StatusMsg.StatusMsg_135, e.getMessage());
		}
	}

	//批量删除导入的众包项目
	@Transactional
	public SmartResult delBatchImportProject(BaseListFormBean<Integer> formBean) {
		if (null == formBean || null == formBean.getReqdata()) {
			return errorParamSmartResult();
		}
		List<Integer> idList = formBean.getReqdata();
		for (Integer id : idList) {
			//查询项目
			CrowdsourceProject project = new CrowdsourceProject().selectById(id);
			if (null != project && null != project.getSupplementTime()) {
				//获取项目流水
				CrowdsourceTradeRecord tradeRecord = new CrowdsourceTradeRecord().selectOne(
						Condition.create().eq("projectid", project.getProjectid()));
				//获取项目成员
				List<CrowdsourceProjectItem> itemList = new CrowdsourceProjectItem().selectList(
						Condition.create().eq("projectid", project.getProjectid()));
				//获取项目成员流水
				List<CrowdsourceTradeRecordItem> tradeRecordItemList = new CrowdsourceTradeRecordItem().selectList(
						Condition.create().eq("projectid", project.getProjectid()));
				//逻辑删除项目
				if (!project.setDeleted(1).updateById()) {
					LogUtil.error("批量删除导入的众包项目-删除项目失败！项目ID：" + id);
					continue;
				}
				//逻辑删除项目流水
				if (!tradeRecord.setDeleted(1).updateById()) {
					LogUtil.error("批量删除导入的众包项目-删除项目流水失败！项目ID：" + id);
					continue;
				}
				//逻辑删除项目成员信息
				itemList.forEach(item -> {
					if (!item.setDeleted(1).updateById()) {
						LogUtil.error("批量删除导入的众包项目-删除项目成员失败！ID：" + item.getId());
					}
				});
				//逻辑删除项目成员流水
				tradeRecordItemList.forEach(record -> {
					if (!record.setDeleted(1).updateById()) {
						LogUtil.error("批量删除导入的众包项目-删除项目成员流水失败！ID：" + record.getId());
					}
				});
				//处理合伙人分佣信息
				List<PartnerBrokerage> brokerageList = new PartnerBrokerage().selectList(
						Condition.create().eq("projectid", project.getProjectid()).eq("project_type", 2));
				if (null != brokerageList && brokerageList.size() > 0) {
					for (PartnerBrokerage brokerage : brokerageList) {
						//合伙人佣金状态如果有对应的佣金记录，并且已结算已提现，提示这条众包项目合伙人佣金已提现，不能删除
						if (PartnerBrokerageType.CROWDSOURCE == brokerage.getPartnerType() &&
								PartnerBrokerageState.WITHDRAWED == brokerage.getState()) {
							LogUtil.error("批量删除导入的众包项目-删除合伙人分佣信息失败！ID：" + brokerage.getBrokerageid());
							//回滚以上操作
							TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
							return smartResult(StatusMsg.StatusMsg_649);
						}
						//删除分佣信息
						if (!brokerage.setDeleted(1).updateById()) {
							LogUtil.error("批量删除导入的众包项目-删除合伙人分佣信息失败！ID：" + brokerage.getBrokerageid());
						}
						//刷新项目完成时间所在月份的合伙人月份成本分佣统计
						partnerCrowdsourceCostService.recordPartnerCrowdsourceCost(brokerage.getPartnerid(), DateUtil.getDateMonthBeginDate(project.getFinishtime()));
						//获取合伙人分佣流水
						PartnerAccountflow accountflow = new PartnerAccountflow().selectOne(Condition.create()
								.eq("partnerid", brokerage.getPartnerid())
								.eq("projectid", project.getProjectid())
								.eq("flowtype", 1)
								.eq("amounttype", brokerage.getPartnerType()));
						if (null != accountflow) {
							if (!accountflow.deleteById()) {
								LogUtil.error("批量删除导入的众包项目-删除合伙人分佣流水失败！ID：" + accountflow.getId());
							}
						}
					}
				}

				//加回企业余额
				CompanyPayment companyPayment = companyPaymentMapper.getCompanyPayment(project.getCompid(), project.getPayId());
				if (companyPayment == null) return smartResult(StatusMsg.StatusMsg_330);

				BigDecimal projectAmount = project.getProjectTotalPayableAmount();
				BigDecimal beforeBalance = companyPayment.getBalance();
				//企业账户余额增加退款金额
				BigDecimal currBalance = beforeBalance.add(projectAmount);
				companyPayment.setBalance(currBalance).updateById();
				//生成企业流水账目
				boolean companyFlow = new CompanyAccountflow()
						.setFlowAmount(projectAmount)
						.setPayId(companyPayment.getPayId())
						.setBeforeBalance(beforeBalance)
						.setCurrBalance(currBalance)
						.setBeforeFrozenBalance(companyPayment.getFrozenBalance())
						.setCurrFrozenBalance(companyPayment.getFrozenBalance())
						.setFlowname(project.getProjectName() + "项目取消").setFlowtype(1)
						.setBizid(project.getProjectid())
						.setBizType(project.getWorkType() == Constants.WORK_TYPE_1 ? CompanyAccountFlowBizType.CROWDSOURCE_PROJECT : CompanyAccountFlowBizType.CROWDSOURCE_ODD_PROJECT)
						.setCompid(project.getCompid())
						.setPayId(project.getPayId())
						.insert();
				if (!companyFlow) {
					return smartResult(StatusMsg.StatusMsg_199);
				}
				// 删除智众包发票
				new Invoice().delete(Condition.create().eq("projectid", id).eq("project_type", ProjectType.CROWDSOURCE));
				// 删除众包成本发票
				if (project.getWorkType() == null || project.getWorkType() == Constants.WORK_TYPE_1) {
					new CrowdsourceInvoice().delete(Condition.create().eq("projectid", id));
				} else {
					new ContractorInvoice().delete(Condition.create().eq("projectid", id));
				}
			} else {
				LogUtil.error("批量删除导入的众包项目-项目不符合条件！项目ID：" + id);
			}
		}
		return smartResult();
	}

	/**
	 * 推送发包方
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult pushEmployer(BaseSimpleFormBean<Integer> formBean) {
		LogUtil.info("进入推送发包方阶段");
		if (null == formBean || null == formBean.getReqdata()) {
			return errorParamSmartResult();
		}
		int projectid = formBean.getReqdata();
		//获取项目详情
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(projectid);
		if (null == crowdsourceProject) {
			return smartResult(StatusMsg.StatusMsg_606);
		}
		//获取公司信息
		Company company = new Company().selectById(crowdsourceProject.getCompid());
		if (null == company) {
			return smartResult(StatusMsg.StatusMsg_302);
		}
		//获取企业详细信息
		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", company.getCompid()));
		if (null == companyAccount) {
			return smartResult(StatusMsg.StatusMsg_313);
		}
		//推送的时候判断合同是否到期，到期的话提示更新合同日期，更新日期后需要按新的日期重新生成项目合同编号；
		if (null == companyAccount.getContractStartDate() || null == companyAccount.getContractEndDate()) {
			LogUtil.info("推送发包方阶段：请先设置该发票关联的企业的合同起止日期！企业compid：" + companyAccount.getCompid());
			return smartResult(StatusMsg.StatusMsg_340);
		}
		int days = DateUtil.getIntervalDays(companyAccount.getContractEndDate(), new Date());
		if (days > 0) {
			//企业的合同起止日期已到期
			//到期了 需要更新新的 项目编号、项目流水号； 要重新推送 企业和商户的合同 生成 所以 直接把项目编号、项目流水号 更新为空字符串。然后 下一步推送项目时候 会判断项目编号和项目流水号 是否为空，为空的话就会重新生成
			companyAccount.setProjectBidno("").setProjectSerialNumber("").updateById();
			LogUtil.info("推送发包方阶段：企业的合同起止日期已到期，请先重新设置!企业compid：" + companyAccount.getCompid());
			return smartResult(StatusMsg.StatusMsg_341);
		}
		RestTemplate restTemplate = new RestTemplate();
		//如果没有推送过，就推送，推送过的话就直接推送项目
		if (StringUtil.isEmpty(companyAccount.getFirmid())) {
			//判断必填项
			if (StringUtil.isAnyEmpty(companyAccount.getRealname(), companyAccount.getIdno(), company.getCompaddress(),
					company.getContactname())) {
				LogUtil.error("推送发包方错误！企业真实姓名或者身份证号，经营地址，联系人名字至少有一个为空!");
				return smartResult(StatusMsg.StatusMsg_334);
			}
			if (0 == companyAccount.getEconomyCategoryId()) {
				return smartResult(StatusMsg.StatusMsg_332);
			}
			//判断男女
			int sex = 0;
			if (2 == company.getSex()) {
				sex = 1;
			}
			//构建发包方信息
			PushEmployerFormBean pushEmployerFormBean = new PushEmployerFormBean();
			pushEmployerFormBean.setFIRMNAME(company.getCompname())
					.setZUZHJGDM(company.getCreditcode())
					.setFARNNAME(companyAccount.getRealname())
					.setFARNXNGB(String.valueOf(sex))
					.setFARNZJLX("A")
					.setFARNZJNO(companyAccount.getIdno())
					.setFARNHKPROVID("2")
					.setFARNHKCITYID("33")
					.setFARNHKREGIID("383")
					.setFARNJZDZ(company.getCompaddress())
					.setLXRNNAME(company.getContactname())
					.setCATEGORYID(String.valueOf(companyAccount.getEconomyCategoryId()));
			BaseSimpleFormBean<PushEmployerFormBean> pushEmployer = new BaseSimpleFormBean<>();
			pushEmployer.setReqdata(pushEmployerFormBean);
			//推送发包方
			SmartResult result = restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getPushEmployer(), pushEmployer,
					SmartResult.class);
			if (result != null && result.getState() == StatusMsg.StatusMsg_100.getState()) {
				JSONObject object = result.toJson().getJSONObject("object");
				if (StringUtil.isEmpty(object.getString("FIRMID"))) {
					LogUtil.error("推送发包方错误！返回信息：" + object.toJSONString());
					return smartResult(StatusMsg.StatusMsg_199);
				} else {
					//更新企业
					companyAccount.setFirmid(object.getString("FIRMID"));
					if (!companyAccount.updateById()) {
						LogUtil.error("更新企业失败！返回的发包方编号：" + object.getString("FIRMID"));
						return smartResult(StatusMsg.StatusMsg_199);
					} else {
						return smartResult(object.getString("FIRMID"));
					}
				}
			} else {
				return result;
			}
		} else {
			return smartResult(companyAccount.getFirmid());
		}
	}

	/**
	 * 推送项目
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult pushProject(BaseSimpleFormBean<ApplyInvoiceFormBean> formBean, HttpServletResponse response) {
		LogUtil.info("进入推送项目阶段");
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata().getProjectId() ||
				StringUtil.isEmpty(formBean.getReqdata().getGongQingInvoiceContent()) ||
				StringUtil.isEmpty(formBean.getReqdata().getEconomicSecond()) ||
				StringUtil.isEmpty(formBean.getReqdata().getInvoiceType())) {
			return errorParamSmartResult();
		}
		ApplyInvoiceFormBean applyInvoiceFormBean = formBean.getReqdata();
		//获取项目详情
		int projectid = applyInvoiceFormBean.getProjectId();
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(projectid);
		if (null == crowdsourceProject) {
			return smartResult(StatusMsg.StatusMsg_606);
		}
		//获取企业详细信息
		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", crowdsourceProject.getCompid()));
		if (null == companyAccount) {
			return smartResult(StatusMsg.StatusMsg_313);
		}

		//获取众智包项目人员信息
		List<CrowdsourceProjectItem> crowdsourceProjectItemList = crowdsourceProjectItemMapper.queryCrowdsourceProjectItem(projectid);
		if (null == crowdsourceProjectItemList || 0 == crowdsourceProjectItemList.size()) {
			return smartResult(StatusMsg.StatusMsg_610);
		}
		int userType = crowdsourceProjectItemList.get(0).getUserType();
		if (1 < crowdsourceProjectItemList.size()) {
			//判断该智众包项目中是否同时存在自然人和创客
			for (CrowdsourceProjectItem crowdsourceProjectItem : crowdsourceProjectItemList) {
				if (crowdsourceProjectItem.getUserType() != userType) {
					return smartResult(StatusMsg.StatusMsg_625);
				}
			}
		}

		List<CrowdsourceAccount> crowdsourceAccountList = new ArrayList<>();
		List<MakerStudio> makerStudioList = new ArrayList<>();
		//获取项目绑定的自然人/创客
		if (1 == userType) {
			crowdsourceAccountList = crowdsourceAccountMapper.queryCrowdsourceInfo(projectid);
		} else if (2 == userType) {
			makerStudioList = makerStudioMapper.queryMakerStudioInfo(projectid);
		}

		RestTemplate restTemplate = new RestTemplate();
		//判断有没有推送过项目，如果推送过就不用再次推送了
		if (StringUtil.isEmpty(crowdsourceProject.getProjectBidno())) {
			try {
				//生成一份合同
				File contractDocFile = docService.getGongQingContractFile(crowdsourceAccountList, makerStudioList, crowdsourceProject,
						response, applyInvoiceFormBean.getGongQingInvoiceContent());
				//将合同转为PDF并转为Base64
				String fileName = contractDocFile.getName().substring(0, contractDocFile.getName().lastIndexOf(".")) + "-" +
						System.currentTimeMillis();
				String format = "yyyyMMdd";
				//文件夹名称
				String folderName = "/" + DateUtil.DateToStr(format, new Date());
				String path = docConfig.getGongqingcheng() + folderName + "/" + fileName + ".pdf";
				DocUtils.convertDocxToPDF(contractDocFile, path);

				LogUtil.info("生成的word合同转为pdf存放的路径" + path);
				String wordInfo = Base64.encodeBase64File(path);
				//构建项目信息
				PushProjectFormBean pushProjectFormBean = new PushProjectFormBean();
				pushProjectFormBean.setFILEBASE(wordInfo)
						.setBIDTITLE(crowdsourceProject.getProjectName() + crowdsourceProject.getProjectid())
						.setINVOICETYPE(applyInvoiceFormBean.getInvoiceType())
						.setINVOICEINFO(applyInvoiceFormBean.getGongQingInvoiceContent())
						.setFIRMID(companyAccount.getFirmid())
						.setFILETYPE("pdf")
						.setFILENAME(fileName)
						.setCATEGORYID(applyInvoiceFormBean.getEconomicSecond());
				BaseSimpleFormBean<PushProjectFormBean> pushProject = new BaseSimpleFormBean<>();
				pushProject.setReqdata(pushProjectFormBean);
				//推送项目
				SmartResult result = restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getZddPushProject(),
						pushProject, SmartResult.class);
				if (result != null && result.getState() == StatusMsg.StatusMsg_100.getState()) {
					//					JSONObject object = (JSONObject) result.getObject();
					JSONObject object = result.toJson().getJSONObject("object");
					if (StringUtil.isEmpty(object.getString("BIDNO")) || StringUtil.isEmpty(object.getString("PLATSRL"))) {
						LogUtil.error("推送项目错误！返回信息：" + object.toJSONString());
						return smartResult(StatusMsg.StatusMsg_199);
					} else {
						//更新智众包项目
						//项目编号和项目流水号 一级二级经济分类 开票内容 发票类型
						crowdsourceProject.setProjectBidno(object.getString("BIDNO"))
								.setProjectSerialNumber(object.getString("PLATSRL"))
								.setGongQingInvoiceContent(applyInvoiceFormBean.getGongQingInvoiceContent())
								.setEconomicFirst(applyInvoiceFormBean.getEconomicFirst())
								.setEconomicSecond(applyInvoiceFormBean.getEconomicSecond())
								.setInvoiceType(applyInvoiceFormBean.getInvoiceType())
								.setContractPath(path);
						if (!crowdsourceProject.updateById()) {
							LogUtil.error("更新项目失败！返回的项目编号：" + object.getString("BIDNO") + "，返回的项目流水号：" + object.getString("PLATSRL"));
							return smartResult(StatusMsg.StatusMsg_199);
						}
						return smartResult();
					}
				} else {
					return result;
				}
			} catch (Exception e) {
				e.printStackTrace();
				LogUtil.error("Word转PDF失败！");
				return smartResult(StatusMsg.StatusMsg_199);
			}
		}
		return smartResult();
	}

	/**
	 * 推送合同
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult pushContract(BaseSimpleFormBean<Integer> formBean) {
		LogUtil.info("进入推送推送合同阶段");
		if (null == formBean || null == formBean.getReqdata()) {
			return errorParamSmartResult();
		}
		int projectid = formBean.getReqdata();
		//获取项目详情
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(projectid);
		if (null == crowdsourceProject) {
			return smartResult(StatusMsg.StatusMsg_606);
		}
		//获取项目绑定的自然人/创客
		List<CrowdsourceRelevantInfoDto> relevantInfoDtoList = crowdsourceProjectItemMapper.queryCrowdsourceRelevantInfo(projectid);
		//判断自然人/创客是否都在共青城注册
		for (CrowdsourceRelevantInfoDto relevantInfoDto : relevantInfoDtoList) {
			if (StringUtil.isEmpty(relevantInfoDto.getNaturalNumber())) {
				return smartResult(StatusMsg.StatusMsg_616);
			}
		}
		RestTemplate restTemplate = new RestTemplate();
		try {
			for (CrowdsourceRelevantInfoDto relevantInfo : relevantInfoDtoList) {
				//获取自然人/创客开票信息
				CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectOne(
						Condition.create().eq("projectid", projectid).eq("crowdsourceid", relevantInfo.getCrowdsourceid()));
				if (null == crowdsourceInvoice) {
					return smartResult(StatusMsg.StatusMsg_617);
				}
				PushContractFormBean pushContractFormBean = new PushContractFormBean();
				if (2 == relevantInfo.getUserType()) {
					//个体户必须传合同附件 自然人不用
					String wordInfo = Base64.encodeBase64File(crowdsourceProject.getContractPath());
					pushContractFormBean.setFILEBASE(wordInfo).setFILETYPE("pdf").setFILENAME(crowdsourceProject.getProjectName());
				}
				pushContractFormBean.setFIRMID(relevantInfo.getNaturalNumber());
				pushContractFormBean.setBIDPLATSRL(crowdsourceProject.getProjectSerialNumber());
				BaseSimpleFormBean<PushContractFormBean> pushContract = new BaseSimpleFormBean<>();
				pushContract.setReqdata(pushContractFormBean);
				//推送合同
				SmartResult result = restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getZddPushContract(),
						pushContract, SmartResult.class);
				if (result != null && result.getState() == StatusMsg.StatusMsg_100.getState()) {
					//				JSONObject object = (JSONObject) result.getObject();
					JSONObject object = result.toJson().getJSONObject("object");
					if (StringUtil.isEmpty(object.getString("FILENO")) || StringUtil.isEmpty(object.getString("PLATSRL"))) {
						LogUtil.error("推送合同错误！返回信息：" + object.toJSONString());
						crowdsourceInvoice.setFailReason(object.toJSONString())
								.setUpdatetime(new Date())
								.setOperator(formBean.getUserid())
								.setOperator(formBean.getUserid());
						crowdsourceInvoice.updateById();
						return smartResult(StatusMsg.StatusMsg_199);
					} else {
						crowdsourceInvoice.setStatus(3)
								.setContractNumber(object.getString("FILENO"))
								.setContractSerialNumber(object.getString("PLATSRL"))
								.setUpdatetime(new Date())
								.setOperator(formBean.getUserid());
						if (!crowdsourceInvoice.updateById()) {
							LogUtil.error(
									"更新自然人/创客开票信息失败！返回的合同编号：" + object.getString("FILENO") + ",返回的系统流水号：" + object.getString("PLATSRL"));
							return smartResult(StatusMsg.StatusMsg_199);
						}
					}
				} else {
					crowdsourceInvoice.setFailReason("调用无忧云控推送合同接口失败！").setUpdatetime(new Date()).setOperator(formBean.getUserid());
					crowdsourceInvoice.updateById();
					return result;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.error("文件转base64失败！");
			return smartResult(StatusMsg.StatusMsg_199);
		}
		return smartResult();
	}

	/**
	 * 推送结算
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult pushSettlement(BaseSimpleFormBean<Integer> formBean) {
		LogUtil.info("进入推送推送结算阶段");
		if (null == formBean || null == formBean.getReqdata()) {
			return errorParamSmartResult();
		}
		int projectid = formBean.getReqdata();
		//获取项目详情
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(projectid);
		if (null == crowdsourceProject) {
			return smartResult(StatusMsg.StatusMsg_606);
		}
		//获取项目绑定的自然人/创客
		List<CrowdsourceRelevantInfoDto> relevantInfoDtoList = crowdsourceProjectItemMapper.queryCrowdsourceRelevantInfo(projectid);
		//判断自然人/创客是否都在共青城注册
		for (CrowdsourceRelevantInfoDto relevantInfoDto : relevantInfoDtoList) {
			if (StringUtil.isEmpty(relevantInfoDto.getNaturalNumber())) {
				return smartResult(StatusMsg.StatusMsg_616);
			}
		}
		RestTemplate restTemplate = new RestTemplate();
		for (CrowdsourceRelevantInfoDto relevantInfo : relevantInfoDtoList) {
			//获取自然人/创客开票信息
			CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectOne(
					Condition.create().eq("projectid", projectid).eq("crowdsourceid", relevantInfo.getCrowdsourceid()));
			if (null == crowdsourceInvoice) {
				return smartResult(StatusMsg.StatusMsg_617);
			}
			PushSettlementFormBean pushSettlementFormBean = new PushSettlementFormBean();
			pushSettlementFormBean.setBIDNO(crowdsourceProject.getProjectBidno())
					.setHTPLATSRL(crowdsourceInvoice.getContractSerialNumber())
					.setFIRMID(relevantInfo.getNaturalNumber())
					.setACCZJNO(relevantInfo.getIdno())
					.setACCID(relevantInfo.getYunKongAcctno())
					.setSETTLEMONEY(relevantInfo.getProjectAmount().doubleValue());
			BaseSimpleFormBean<PushSettlementFormBean> pushSettlement = new BaseSimpleFormBean<>();
			pushSettlement.setReqdata(pushSettlementFormBean);
			//推送结算
			SmartResult result = restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getPushSettlement(),
					pushSettlement, SmartResult.class);
			if (result != null && result.getState() == StatusMsg.StatusMsg_100.getState()) {
				//				JSONObject object = (JSONObject) result.getObject();
				JSONObject object = result.toJson().getJSONObject("object");
				if (StringUtil.isEmpty(object.getString("platstr"))) {
					LogUtil.error("推送结算错误！返回信息：" + object.toJSONString());
					crowdsourceInvoice.setFailReason(object.toJSONString()).setUpdatetime(new Date()).setOperator(formBean.getUserid());
					crowdsourceInvoice.updateById();
					return smartResult(StatusMsg.StatusMsg_199);
				} else {
					crowdsourceInvoice.setStatus(4)
							.setPlatstr(object.getString("platstr"))
							.setState(2)
							.setUpdatetime(new Date())
							.setOperator(formBean.getUserid());
					if (!crowdsourceInvoice.updateById()) {
						LogUtil.error("更新自然人/创客开票信息失败！返回的结算编号：" + object.getString("platstr"));
						return smartResult(StatusMsg.StatusMsg_199);
					}
				}
			} else {
				crowdsourceInvoice.setFailReason("调用无忧云控推送结算接口失败！").setUpdatetime(new Date()).setOperator(formBean.getUserid());
				crowdsourceInvoice.updateById();
				return result;
			}
		}
		return smartResult();
	}

	/**
	 * 自然人申请开票
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult applyForInvoice(BaseSimpleFormBean<ApplyInvoiceFormBean> formBean, HttpServletResponse response) {
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata().getProjectId() ||
				StringUtil.isEmpty(formBean.getReqdata().getGongQingInvoiceContent()) ||
				StringUtil.isEmpty(formBean.getReqdata().getEconomicFirst()) ||
				StringUtil.isEmpty(formBean.getReqdata().getEconomicSecond()) ||
				StringUtil.isEmpty(formBean.getReqdata().getInvoiceType()) || 0 == formBean.getReqdata().getCrowdsourceid()) {
			return errorParamSmartResult();
		}
		ApplyInvoiceFormBean applyInvoiceFormBean = formBean.getReqdata();
		//获取项目详情
		int projectid = applyInvoiceFormBean.getProjectId();
		BaseSimpleFormBean<Integer> projectIdBean = new BaseSimpleFormBean<>();
		projectIdBean.setReqdata(projectid);
		projectIdBean.setUserid(formBean.getUserid());
		//第一步 推送发包方
		SmartResult result = pushEmployer(projectIdBean);
		if (result != null && result.getState() == StatusMsg.StatusMsg_100.getState()) {
			//第二步 推送项目  202010-30注释掉并修改  由于政府那边要求一个项目只能有一个合同并且是一个乙方 所以众包项目做成单条推送
			//			SmartResult result2 = pushProject(formBean,response);
			//2021.01.22   一个企业保存一个项目编号，在合同到期前，这个企业的项目合同都用这个编号，不用重复传文件过去；
			SmartResult result2 = pushProjectSingle(formBean, response);
			if (result2 != null && result2.getState() == StatusMsg.StatusMsg_100.getState()) {
				//第三步 推送合同  202010-30注释掉并修改  由于政府那边要求一个项目只能有一个合同并且是一个乙方 所以众包项目做成单条推送
				//				SmartResult result3 = pushContract(projectIDBean);
				SmartResult result3 = pushContractSingle(formBean, response);
				if (result3 != null && result3.getState() == StatusMsg.StatusMsg_100.getState()) {
					//第四步 推送结算  202010-30注释掉并修改  由于政府那边要求一个项目只能有一个合同并且是一个乙方 所以众包项目做成单条推送
					//					SmartResult result4 = pushSettlement(projectIDBean);
					SmartResult result4 = pushSettlementSingle(formBean);
					if (result4 != null && result4.getState() == StatusMsg.StatusMsg_100.getState()) {
						return smartResult();
					} else {
						return result4;
					}
				} else {
					return result3;
				}
			} else {
				return result2;
			}
		} else {
			return result;
		}
	}

	/**
	 * 完成开票
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult complete(BaseSimpleFormBean<CompleteInvoiceFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getUserid() || 0 == formBean.getReqdata().getProjectId() ||
				0 == formBean.getReqdata().getCrowdsourceid()) {
			return errorParamSmartResult();
		}
		CompleteInvoiceFormBean completeInvoiceFormBean = formBean.getReqdata();
		int projectid = completeInvoiceFormBean.getProjectId();
		int crowdsourceid = completeInvoiceFormBean.getCrowdsourceid();
		//获取项目详情
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(completeInvoiceFormBean.getProjectId());
		if (null == crowdsourceProject) {
			return smartResult(StatusMsg.StatusMsg_606);
		}
		//获取该条发票信息
		CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectOne(
				Condition.create().eq("projectid", projectid).eq("crowdsourceid", crowdsourceid));
		if (null == crowdsourceInvoice) {
			return smartResult(StatusMsg.StatusMsg_617);
		}
		String resultMsg = "当前结算流水号结算单已上传过";
		//上传结算单
		SmartResult electronicReceipt = settlementElectronicReceipt(formBean);
		if ((electronicReceipt != null && electronicReceipt.getState() == StatusMsg.StatusMsg_100.getState()) ||
				(null != electronicReceipt && resultMsg.equals(electronicReceipt.getMsg()))) {
			//上传结算发票
			SmartResult invoicePicture = settlementInvoicePicture(formBean);
			if (invoicePicture != null && invoicePicture.getState() == StatusMsg.StatusMsg_100.getState()) {
				//最后在操作数据库状态等信息
				crowdsourceInvoice.setState(Constants.CROWDSOURCE_INVOICE_STATE_3)
						.setStatus(5)
						.setUpdatetime(new Date())
						.setFinishtime(new Date())
						.setOperator(formBean.getUserid())
						.setElectronicReceipt(completeInvoiceFormBean.getElectronicReceipt())
						.setInvoicePicture(completeInvoiceFormBean.getInvoicePicture())
						.setInvoiceNumber(completeInvoiceFormBean.getInvoiceFaceNumber());
				if (crowdsourceInvoice.updateById()) {
					return smartResult();
				} else {
					return smartResult(StatusMsg.StatusMsg_199);
				}
			} else {
				return invoicePicture;
			}
		} else {
			return electronicReceipt;
		}
	}

	/**
	 * 作废开票
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult invalid(BaseSimpleFormBean<InvalidInvoiceFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata().getProjectId() ||
				0 == formBean.getReqdata().getCrowdsourceid()) {
			return errorParamSmartResult();
		}
		InvalidInvoiceFormBean invalidInvoiceFormBean = formBean.getReqdata();
		int projectid = invalidInvoiceFormBean.getProjectId();
		int crowdsourceid = invalidInvoiceFormBean.getCrowdsourceid();
		//获取项目详情
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(projectid);
		if (null == crowdsourceProject) {
			return smartResult(StatusMsg.StatusMsg_606);
		}

		//获取该条发票信息
		CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectOne(
				Condition.create().eq("projectid", projectid).eq("crowdsourceid", crowdsourceid));
		if (null == crowdsourceInvoice) {
			return smartResult(StatusMsg.StatusMsg_617);
		}

		crowdsourceInvoice.setState(4)
				.setInvalidationReasons(invalidInvoiceFormBean.getInvalidationReasons())
				.setOperator(formBean.getUserid())
				.setUpdatetime(new Date());
		if (crowdsourceInvoice.updateById()) {
			return smartResult();
		} else {
			return smartResult(StatusMsg.StatusMsg_199);
		}
	}

	/**
	 * 推送项目(众包项目分批单条推送)
	 * 个体户：推送项目时候 项目文件为 发包方和商户之间的合同
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult pushProjectSingle(BaseSimpleFormBean<ApplyInvoiceFormBean> formBean, HttpServletResponse response) {
		LogUtil.info("进入推送项目阶段");
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata().getProjectId() ||
				StringUtil.isEmpty(formBean.getReqdata().getGongQingInvoiceContent()) ||
				StringUtil.isEmpty(formBean.getReqdata().getEconomicSecond()) ||
				StringUtil.isEmpty(formBean.getReqdata().getInvoiceType()) || 0 == formBean.getReqdata().getCrowdsourceid()) {
			return errorParamSmartResult();
		}
		ApplyInvoiceFormBean applyInvoiceFormBean = formBean.getReqdata();
		//获取项目详情
		int projectid = applyInvoiceFormBean.getProjectId();
		int crowdsourceid = applyInvoiceFormBean.getCrowdsourceid();
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(projectid);
		if (null == crowdsourceProject) {
			return smartResult(StatusMsg.StatusMsg_606);
		}
		//获取该条发票信息
		CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectOne(
				Condition.create().eq("projectid", projectid).eq("crowdsourceid", crowdsourceid));

		//获取公司信息
		Company company = new Company().selectById(crowdsourceProject.getCompid());
		if (null == company) {
			return smartResult(StatusMsg.StatusMsg_302);
		}

		//获取企业详细信息
		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", crowdsourceProject.getCompid()));
		if (null == companyAccount) {
			return smartResult(StatusMsg.StatusMsg_313);
		}
		if (StringUtil.isAnyEmpty(company.getCompname(), company.getCompaddress(), companyAccount.getRealname(),
				company.getContactphone())) {
			return smartResult(StatusMsg.StatusMsg_338);
		}

		CrowdsourceProjectItem crowdsourceProjectItem = new CrowdsourceProjectItem().selectOne(
				Condition.create().eq("projectid", projectid).eq("userid", crowdsourceid).eq("deleted", 0));
		if (null == crowdsourceProjectItem) {
			return smartResult(StatusMsg.StatusMsg_610);
		}

		RestTemplate restTemplate = new RestTemplate();
		//2021.01.22   一个企业保存一个项目编号和一个项目流水号，在合同有效日期中，这个企业的项目合同都用这个编号和流水号，不用重复传文件过去；
		if (StringUtil.isAnyEmpty(companyAccount.getProjectBidno(), companyAccount.getProjectSerialNumber())) {
			LogUtil.info("推送项目阶段：开始推送该条数据的项目文件！发票数据id：" + crowdsourceInvoice.getId());
			try {
				File contractDocFile = new File("");
				if (1 == crowdsourceProjectItem.getUserType()) {
					//目前自然人开票已经停掉了
					//该条发票对象是自然人
					CrowdsourceAccount crowdsourceAccount = new CrowdsourceAccount().selectOne(
							Condition.create().eq("crowdsourceid", crowdsourceProjectItem.getUserid()));
					if (null == crowdsourceAccount) {
						return smartResult(StatusMsg.StatusMsg_626);
					}
					contractDocFile = docService.getGongQingContractCrowdSourceAccountFile(crowdsourceAccount, crowdsourceProject,
							response,
							applyInvoiceFormBean.getGongQingInvoiceContent());
				} else if (2 == crowdsourceProjectItem.getUserType()) {
					//该条发票对象是个体户
					MakerStudio makerStudio = new MakerStudio().selectOne(
							Condition.create().eq("userid", crowdsourceProjectItem.getUserid()));
					if (null == makerStudio) {
						return smartResult(StatusMsg.StatusMsg_627);
					}
					//					contractDocFile = docService.getGongQingContracMakerFile(makerStudio,crowdsourceProject, response,
					//					applyInvoiceFormBean.getGongQingInvoiceContent());
					//生成的是 发包方和商户的 合同
					contractDocFile = docService.getBusinessContractFile(response, company, companyAccount, crowdsourceProject);
				} else {
					return smartResult(StatusMsg.StatusMsg_630);
				}

				//将合同转为PDF并转为Base64
				String fileName = contractDocFile.getName().substring(0, contractDocFile.getName().lastIndexOf(".")) + "-" +
						System.currentTimeMillis();
				String format = "yyyyMMdd";
				//文件夹名称
				String folderName = "/" + DateUtil.DateToStr(format, new Date());
				String path = docConfig.getGongqingcheng() + folderName + "/" + fileName + ".pdf";
				DocUtils.convertDocxToPDF(contractDocFile, path);

				LogUtil.info("推送项目阶段：生成的发包方和商户的word合同转为pdf存放的路径" + path);
				String wordInfo = Base64.encodeBase64File(path);
				//构建项目信息
				PushProjectFormBean pushProjectFormBean = new PushProjectFormBean();
				//项目名称：项目名称+企业id+合同的开始日期
				String strName = DateUtil.DateToStr(DateUtil.FORMAT_STYLE_8, companyAccount.getContractStartDate());
				pushProjectFormBean.setFILEBASE(wordInfo)
						.setBIDTITLE(crowdsourceProject.getProjectName() + companyAccount.getCompid() + strName)
						.setINVOICETYPE(applyInvoiceFormBean.getInvoiceType())
						.setINVOICEINFO(applyInvoiceFormBean.getGongQingInvoiceContent())
						.setFIRMID(companyAccount.getFirmid())
						.setFILETYPE("pdf")
						.setFILENAME(fileName)
						.setCATEGORYID(applyInvoiceFormBean.getEconomicSecond());
				BaseSimpleFormBean<PushProjectFormBean> pushProject = new BaseSimpleFormBean<>();
				pushProject.setReqdata(pushProjectFormBean);
				//推送项目
				SmartResult result = restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getZddPushProject(),
						pushProject, SmartResult.class);
				if (result != null && result.getState() == StatusMsg.StatusMsg_100.getState()) {
					JSONObject object = result.toJson().getJSONObject("object");
					if (StringUtil.isEmpty(object.getString("BIDNO")) || StringUtil.isEmpty(object.getString("PLATSRL"))) {
						LogUtil.error("推送项目错误！返回信息：" + object.toJSONString());
						return smartResult(StatusMsg.StatusMsg_199);
					} else {
						//更新智众包项目单条发票 记录
						//项目编号和项目流水号 一级二级经济分类 开票内容 发票类型 推送的 发包方与商户合同
						crowdsourceInvoice.setStatus(2)
								.setProjectBidno(object.getString("BIDNO"))
								.setProjectSerialNumber(object.getString("PLATSRL"))
								.setGongQingInvoiceContent(applyInvoiceFormBean.getGongQingInvoiceContent())
								.setEconomicFirst(applyInvoiceFormBean.getEconomicFirst())
								.setEconomicSecond(applyInvoiceFormBean.getEconomicSecond())
								.setInvoiceType(applyInvoiceFormBean.getInvoiceType())
								.setBusinessContractPath(path);
						if (!crowdsourceInvoice.updateById()) {
							LogUtil.error("更新开票信息失败！返回的项目编号：" + object.getString("BIDNO") + "，返回的项目流水号：" + object.getString("PLATSRL"));
							return smartResult(StatusMsg.StatusMsg_199);
						}
						//在企业详细信息中保存 项目编号  吧推送过去的发包方和商户的合同也保存下来
						companyAccount.setProjectBidno(object.getString("BIDNO"))
								.setBusinessContractPath(path)
								.setProjectSerialNumber(object.getString("PLATSRL"));
						if (!companyAccount.updateById()) {
							return smartResult(StatusMsg.StatusMsg_199);
						}
						return smartResult();
					}
				} else {
					return result;
				}
			} catch (Exception e) {
				e.printStackTrace();
				LogUtil.error("Word转PDF失败！");
				return smartResult(StatusMsg.StatusMsg_199);
			}
		} else {
			//更新智众包项目单条发票 记录
			//项目编号和项目流水号 一级二级经济分类 开票内容 发票类型 推送的 发包方与商户合同
			crowdsourceInvoice.setStatus(2)
					.setProjectBidno(companyAccount.getProjectBidno())
					.setProjectSerialNumber(companyAccount.getProjectSerialNumber())
					.setGongQingInvoiceContent(applyInvoiceFormBean.getGongQingInvoiceContent())
					.setEconomicFirst(applyInvoiceFormBean.getEconomicFirst())
					.setEconomicSecond(applyInvoiceFormBean.getEconomicSecond())
					.setInvoiceType(applyInvoiceFormBean.getInvoiceType())
					.setBusinessContractPath(companyAccount.getBusinessContractPath())
					.updateById();
			LogUtil.info("推送项目阶段：目前该企业已有固定的项目编号和项目流水号，不再继续推送项目，直接推送合同！该企业compid：" + companyAccount.getCompid());
			return smartResult();
		}
	}

	/**
	 * 推送合同(众包项目分批单条推送)
	 * 个体户：推送合同 必须传合同附件 合同为 个体户和商户之间的合同
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult pushContractSingle(BaseSimpleFormBean<ApplyInvoiceFormBean> formBean, HttpServletResponse response) {
		LogUtil.info("进入推送合同阶段");
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata().getCrowdsourceid() ||
				0 == formBean.getReqdata().getProjectId()) {
			return errorParamSmartResult();
		}
		ApplyInvoiceFormBean applyInvoiceFormBean = formBean.getReqdata();
		int projectid = applyInvoiceFormBean.getProjectId();
		int crowdsourceid = applyInvoiceFormBean.getCrowdsourceid();
		//获取项目详情
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(projectid);
		if (null == crowdsourceProject) {
			return smartResult(StatusMsg.StatusMsg_606);
		}

		//获取企业详细信息
		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", crowdsourceProject.getCompid()));
		if (null == companyAccount) {
			return smartResult(StatusMsg.StatusMsg_313);
		}
		//获取该条发票信息
		CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectOne(
				Condition.create().eq("projectid", projectid).eq("crowdsourceid", crowdsourceid));
		if (null == crowdsourceInvoice) {
			return smartResult(StatusMsg.StatusMsg_617);
		}
		//获取该条项目人员信息
		CrowdsourceProjectItem crowdsourceProjectItem = new CrowdsourceProjectItem().selectOne(
				Condition.create().eq("projectid", projectid).eq("userid", crowdsourceid).eq("deleted", 0));
		if (null == crowdsourceProjectItem) {
			return smartResult(StatusMsg.StatusMsg_610);
		}
		RestTemplate restTemplate = new RestTemplate();
		//如果已经有了合同编号和合同流水号 说明已经推送过了 直接走下一步
		if (StringUtil.isAnyEmpty(crowdsourceInvoice.getContractNumber(), crowdsourceInvoice.getContractSerialNumber())) {
			LogUtil.info("进入推送合同阶段：开始推送合同！");
			try {
				PushContractFormBean pushContractFormBean = new PushContractFormBean();
				if (2 == crowdsourceProjectItem.getUserType()) {
					//个体户
					MakerAccount makerAccount = new MakerAccount().selectOne(
							Condition.create().eq("userid", crowdsourceProjectItem.getUserid()));
					if (null == makerAccount) {
						return smartResult(StatusMsg.StatusMsg_628);
					}
					if (StringUtil.isEmpty(makerAccount.getIndividualAccountNumber())) {
						//判断是否存在共青城个体户编号
						return smartResult(StatusMsg.StatusMsg_224);
					}
					//该条发票对象是个体户
					MakerStudio makerStudio = new MakerStudio().selectOne(
							Condition.create().eq("userid", crowdsourceProjectItem.getUserid()));
					if (null == makerStudio) {
						return smartResult(StatusMsg.StatusMsg_627);
					}
					File contractDocFile = docService.getGongQingContracMakerFile(makerStudio, crowdsourceProject, response,
							applyInvoiceFormBean.getGongQingInvoiceContent());
					//将合同转为PDF并转为Base64
					String fileName = contractDocFile.getName().substring(0, contractDocFile.getName().lastIndexOf(".")) + "-" +
							System.currentTimeMillis();
					String format = "yyyyMMdd";
					//文件夹名称
					String folderName = "/" + DateUtil.DateToStr(format, new Date());
					String path = docConfig.getGongqingcheng() + folderName + "/" + fileName + ".pdf";
					DocUtils.convertDocxToPDF(contractDocFile, path);
					crowdsourceInvoice.setContractPath(path).updateById();
					LogUtil.info("生成的word合同转为pdf存放的路径" + path);
					String wordInfo = Base64.encodeBase64File(path);
					//个体户必须传合同附件 这里的合同为个体户和商户（武圣）之间的合同
					pushContractFormBean.setFILEBASE(wordInfo)
							.setFILETYPE("pdf")
							.setFILENAME(crowdsourceProject.getProjectName() + crowdsourceProjectItem.getUserid())
							.setFIRMID(makerAccount.getIndividualAccountNumber());
				} else if (1 == crowdsourceProjectItem.getUserType()) {
					//自然人
					CrowdsourceAccount crowdsourceAccount = new CrowdsourceAccount().selectOne(
							Condition.create().eq("crowdsourceid", crowdsourceProjectItem.getUserid()));
					if (null == crowdsourceAccount) {
						return smartResult(StatusMsg.StatusMsg_626);
					}
					if (StringUtil.isEmpty(crowdsourceAccount.getNaturalNumber())) {
						//判断自然人的共青城自然人编号
						return smartResult(StatusMsg.StatusMsg_629);
					}
					pushContractFormBean.setFIRMID(crowdsourceAccount.getNaturalNumber());
				} else {
					return smartResult(StatusMsg.StatusMsg_630);
				}
				//取企业表保存的项目流水号
				pushContractFormBean.setBIDPLATSRL(companyAccount.getProjectSerialNumber());
				BaseSimpleFormBean<PushContractFormBean> pushContract = new BaseSimpleFormBean<>();
				pushContract.setReqdata(pushContractFormBean);
				//推送合同
				SmartResult result = restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getZddPushContract(),
						pushContract, SmartResult.class);
				if (result != null && result.getState() == StatusMsg.StatusMsg_100.getState()) {
					JSONObject object = result.toJson().getJSONObject("object");
					if (StringUtil.isEmpty(object.getString("FILENO")) || StringUtil.isEmpty(object.getString("PLATSRL"))) {
						LogUtil.error("推送合同错误！返回信息：" + object.toJSONString());
						crowdsourceInvoice.setFailReason(object.toJSONString())
								.setUpdatetime(new Date())
								.setOperator(formBean.getUserid())
								.setOperator(formBean.getUserid());
						crowdsourceInvoice.updateById();
						return smartResult(StatusMsg.StatusMsg_199);
					} else {
						crowdsourceInvoice.setStatus(3)
								.setContractNumber(object.getString("FILENO"))
								.setContractSerialNumber(object.getString("PLATSRL"))
								.setUpdatetime(new Date())
								.setOperator(formBean.getUserid());
						if (!crowdsourceInvoice.updateById()) {
							LogUtil.error(
									"更新自然人/创客开票信息失败！返回的合同编号：" + object.getString("FILENO") + ",返回的系统流水号：" + object.getString("PLATSRL"));
							return smartResult(StatusMsg.StatusMsg_199);
						}
					}
				} else {
					crowdsourceInvoice.setFailReason("调用无忧云控推送合同接口失败！").setUpdatetime(new Date()).setOperator(formBean.getUserid());
					crowdsourceInvoice.updateById();
					return result;
				}

			} catch (Exception e) {
				e.printStackTrace();
				LogUtil.error("文件转base64失败！");
				return smartResult(StatusMsg.StatusMsg_199);
			}
		}
		return smartResult();
	}

	/**
	 * 推送结算(众包项目分批单条推送)
	 *
	 * @param formBean
	 * @return
	 */
	public synchronized SmartResult pushSettlementSingle(BaseSimpleFormBean<ApplyInvoiceFormBean> formBean) {
		LogUtil.info("进入推送结算阶段");
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata().getCrowdsourceid() ||
				0 == formBean.getReqdata().getProjectId()) {
			return errorParamSmartResult();
		}
		ApplyInvoiceFormBean applyInvoiceFormBean = formBean.getReqdata();
		int projectid = applyInvoiceFormBean.getProjectId();
		int crowdsourceid = applyInvoiceFormBean.getCrowdsourceid();
		//获取该条发票信息
		CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectOne(
				Condition.create().eq("projectid", projectid).eq("crowdsourceid", crowdsourceid));
		if (null == crowdsourceInvoice) {
			return smartResult(StatusMsg.StatusMsg_617);
		}

		//获取项目详情
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(projectid);
		if (null == crowdsourceProject) {
			return smartResult(StatusMsg.StatusMsg_606);
		}
		//获取企业详细信息
		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", crowdsourceProject.getCompid()));
		if (null == companyAccount) {
			return smartResult(StatusMsg.StatusMsg_313);
		}
		if (StringUtil.isEmpty(companyAccount.getProjectBidno())) {
			LogUtil.info("推送结算阶段：该发票关联的企业对应的项目编号为空，发票id：" + crowdsourceInvoice.getId() + ",对应的企业id：" + companyAccount.getCompid());
			return smartResult(StatusMsg.StatusMsg_342);
		}

		if (StringUtil.isEmpty(crowdsourceInvoice.getPlatstr())) {
			//获取该条项目人员信息
			CrowdsourceProjectItem crowdsourceProjectItem = new CrowdsourceProjectItem().selectOne(
					Condition.create().eq("projectid", projectid).eq("userid", crowdsourceid).eq("deleted", 0));
			if (null == crowdsourceProjectItem) {
				return smartResult(StatusMsg.StatusMsg_610);
			}
			PushSettlementFormBean pushSettlementFormBean = new PushSettlementFormBean();
			//取企业表保存的项目编号
			pushSettlementFormBean.setBIDNO(companyAccount.getProjectBidno())
					.setHTPLATSRL(crowdsourceInvoice.getContractSerialNumber())
					.setSETTLEMONEY(crowdsourceInvoice.getProjectAmount().doubleValue());
			if (2 == crowdsourceProjectItem.getUserType()) {
				//个体户
				MakerAccount makerAccount = new MakerAccount().selectOne(
						Condition.create().eq("userid", crowdsourceProjectItem.getUserid()));
				MakerBankcard makerBankcard = new MakerBankcard().selectOne(
						Condition.create().eq("userid", crowdsourceProjectItem.getUserid()).eq("state", 1));
				if (null == makerAccount) {
					return smartResult(StatusMsg.StatusMsg_628);
				}
				if (null == makerBankcard) {
					return smartResult(StatusMsg.StatusMsg_226);
				}
				//如果该个体户 的银行卡信息 没有在共青城保存过
				if (StringUtil.isEmpty(makerBankcard.getYunkongAcctno())) {
					//在共青城那边保存银行信息
					SmartResult resultBank = saveBank(makerAccount.getIndividualAccountNumber(), makerBankcard.getAcctno());
					if (resultBank != null && resultBank.getState() == StatusMsg.StatusMsg_100.getState()) {
						String yunKongId = resultBank.getObject().toString();
						makerBankcard.setYunkongId(yunKongId).setYunkongAcctno(makerBankcard.getAcctno()).updateById();
					} else {
						com.info.zhiduoduo.common.utils.LogUtil.error("推送结算时保存银行卡信息错误！");
						return resultBank;
					}
				}
				if (StringUtil.isAnyEmpty(makerAccount.getIndividualAccountNumber(), makerAccount.getIdno(),
						makerBankcard.getYunkongAcctno())) {
					com.info.zhiduoduo.common.utils.LogUtil.error("推送结算错误！创客的个体户编号或者身份证号，共青城保存的银行卡号至少有一个为空！");
					return smartResult(StatusMsg.StatusMsg_631);
				}
				pushSettlementFormBean.setFIRMID(makerAccount.getIndividualAccountNumber())
						.setACCZJNO(makerAccount.getIdno())
						.setACCID(makerBankcard.getYunkongAcctno());
			} else if (1 == crowdsourceProjectItem.getUserType()) {
				//自然人
				CrowdsourceAccount crowdsourceAccount = new CrowdsourceAccount().selectOne(
						Condition.create().eq("crowdsourceid", crowdsourceProjectItem.getUserid()));
				if (null == crowdsourceAccount) {
					return smartResult(StatusMsg.StatusMsg_626);
				}
				if (StringUtil.isAnyEmpty(crowdsourceAccount.getNaturalNumber(), crowdsourceAccount.getIdno(),
						crowdsourceAccount.getYunkongAcctno())) {
					com.info.zhiduoduo.common.utils.LogUtil.error("推送结算错误！自然人编号或者身份证号，共青城保存的银行卡号至少有一个为空！");
					return smartResult(StatusMsg.StatusMsg_629);
				}
				pushSettlementFormBean.setFIRMID(crowdsourceAccount.getNaturalNumber())
						.setACCZJNO(crowdsourceAccount.getIdno())
						.setACCID(crowdsourceAccount.getYunkongAcctno());
			} else {
				return smartResult(StatusMsg.StatusMsg_630);
			}

			BaseSimpleFormBean<PushSettlementFormBean> pushSettlement = new BaseSimpleFormBean<>();
			pushSettlement.setReqdata(pushSettlementFormBean);
			RestTemplate restTemplate = new RestTemplate();
			//推送结算
			SmartResult result = restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getPushSettlement(),
					pushSettlement, SmartResult.class);
			if (result != null && result.getState() == StatusMsg.StatusMsg_100.getState()) {
				JSONObject object = result.toJson().getJSONObject("object");
				if (StringUtil.isEmpty(object.getString("platstr"))) {
					LogUtil.error("推送结算错误！返回信息：" + object.toJSONString());
					crowdsourceInvoice.setFailReason(object.toJSONString()).setUpdatetime(new Date()).setOperator(formBean.getUserid());
					crowdsourceInvoice.updateById();
					return smartResult(StatusMsg.StatusMsg_199);
				} else {
					crowdsourceInvoice.setStatus(4)
							.setPlatstr(object.getString("platstr"))
							.setState(2)
							.setUpdatetime(new Date())
							.setOperator(formBean.getUserid());
					if (!crowdsourceInvoice.updateById()) {
						LogUtil.error("更新自然人/创客开票信息失败！返回的结算编号：" + object.getString("platstr"));
						return smartResult(StatusMsg.StatusMsg_199);
					}
				}
			} else {
				crowdsourceInvoice.setFailReason("调用无忧云控推送结算接口失败！").setUpdatetime(new Date()).setOperator(formBean.getUserid());
				crowdsourceInvoice.updateById();
				return result;
			}
		}

		return smartResult();
	}

	/**
	 * 更新银行卡信息
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult updateBankInfo(BaseSimpleFormBean<UpdateBankInfoFormBean> formBean) {
		if (null == formBean.getReqdata() || 0 == formBean.getUserid() || StringUtil.isEmpty(formBean.getReqdata().getAcctno()) ||
				0 == formBean.getReqdata().getCrowdsourceid()) {
			return smartResult(StatusMsg.StatusMsg_101);
		}
		UpdateBankInfoFormBean updateBankInfoFormBean = formBean.getReqdata();
		int crowdsourceid = updateBankInfoFormBean.getCrowdsourceid();
		String acctno = updateBankInfoFormBean.getAcctno();
		String bankName = updateBankInfoFormBean.getBankName();
		String openAcctBankName = updateBankInfoFormBean.getOpenAcctBankName();
		Crowdsource crowdsource = new Crowdsource().selectById(crowdsourceid);
		CrowdsourceAccount crowdsourceAccount = new CrowdsourceAccount().selectOne(Condition.create().eq("crowdsourceid", crowdsourceid));
		if (null == crowdsource || null == crowdsourceAccount) {
			return smartResult(StatusMsg.StatusMsg_601);
		}
		if (!StringUtil.isEmpty(bankName)) {
			crowdsourceAccount.setBankname(bankName);
		}
		if (!StringUtil.isEmpty(openAcctBankName)) {
			crowdsourceAccount.setOpenAcctBankName(openAcctBankName);
		}
		// 获取银行卡省份城市
		BankcardResponse.DataDTO bankcardInfo = bankcardService.getBankcardInfo(acctno);
		if (bankcardInfo != null) {
			crowdsourceAccount.setCardName(bankcardInfo.getCardName())
					.setBankProvince(bankcardInfo.getProvince())
					.setBankCity(bankcardInfo.getCity());
		}

		crowdsourceAccount.setAcctno(acctno).updateById();
		if (!StringUtil.isEmpty(crowdsourceAccount.getNaturalNumber())) {
			//在共青城那边修改保存银行信息
			SmartResult resultBank = saveBank(crowdsourceAccount.getNaturalNumber(), acctno);
			if (resultBank != null && resultBank.getState() == StatusMsg.StatusMsg_100.getState()) {
				String yunKongId = resultBank.getObject().toString();
				crowdsourceAccount.setYunkongId(yunKongId).setYunkongAcctno(acctno).updateById();
			} else {
				return resultBank;
			}
		}
		return smartResult();
	}

	/**
	 * 共青城保存银行信息返回的ID
	 *
	 * @param naturalNumber
	 * @param acctNo
	 * @return
	 */
	public SmartResult saveBank(String naturalNumber, String acctNo) {
		RestTemplate restTemplate = new RestTemplate();
		BankInfoSaveFormBean bankInfoSaveFormBean = new BankInfoSaveFormBean();
		bankInfoSaveFormBean.setAcc_id(acctNo).setBank_id("2869").setBank_detail_id("9403").setFirmid(naturalNumber).setAcc_type("2");

		BaseSimpleFormBean<BankInfoSaveFormBean> bankBean = new BaseSimpleFormBean<>();
		bankBean.setReqdata(bankInfoSaveFormBean);
		SmartResult result = restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getBankInfoSave(), bankBean,
				SmartResult.class);
		if (result != null && result.getState() == StatusMsg.StatusMsg_100.getState()) {
			JSONObject object = result.toJson().getJSONObject("object");
			if (StringUtil.isEmpty(object.getString("id"))) {
				com.info.zhiduoduo.common.utils.LogUtil.error("银行信息保存失败！");
				return smartResult(StatusMsg.StatusMsg_199);
			} else {
				return smartResult(object.getString("id"));
			}
		} else {
			if (null != result && StringUtil.isNotEmpty(result.getMsg())) {
				com.info.zhiduoduo.common.utils.LogUtil.error("银行信息保存失败！返回值为:" + result.toString());
				return SmartResult.fail(result.getMsg());
			} else {
				com.info.zhiduoduo.common.utils.LogUtil.error("银行信息保存失败！返回信息为空");
				return smartResult(StatusMsg.StatusMsg_199);
			}
		}
	}

	public void exportJiaYinNaturalPerson(HttpServletResponse response, Long start, Long end) throws Exception {
		Date startDate = null;
		Date endDate = null;
		if (start != null) {
			startDate = new Date(start);
		} else {
			startDate = new Date(0);
		}
		if (end != null) {
			endDate = new Date(end);
		} else {
			endDate = new Date();
		}
		List<ExportJiaYinNaturalPersonDto> naturalPersonDtoList = crowdsourceMapper.queryJiaYinNaturalPerson(startDate, endDate);
		if (null != naturalPersonDtoList && naturalPersonDtoList.size() > 0) {
			for (ExportJiaYinNaturalPersonDto dto : naturalPersonDtoList) {
				//获取身份证正面
				CrowdsourceFile crowdsourceFile1 = new CrowdsourceFile().selectOne(
						Condition.create().eq("crowdsourceid", dto.getCrowdsourceid()).eq("file_type", 1));
				if (null != crowdsourceFile1) {
					dto.setPositiveUrl(new URL(uploadPathConfig.getOssimgurl() + crowdsourceFile1.getFilePath().substring(1)));
				}
				//获取身份证反面
				CrowdsourceFile crowdsourceFile2 = new CrowdsourceFile().selectOne(
						Condition.create().eq("crowdsourceid", dto.getCrowdsourceid()).eq("file_type", 2));
				if (null != crowdsourceFile2) {
					dto.setBackUrl(new URL(uploadPathConfig.getOssimgurl() + crowdsourceFile2.getFilePath().substring(1)));
				}
			}
			String fileName = "嘉银有项目的自然人";
			try {
				EasyExcel.write(getExcelOutPutStream(response, fileName), ExportJiaYinNaturalPersonDto.class)
						.sheet("自然人")
						.doWrite(naturalPersonDtoList);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			LogUtil.info("导出嘉银自然人-没有查询到嘉银自然人！");
		}
	}

	public void compressAllJiaYinInfo(HttpServletResponse response, Long start, Long end, int type) throws IOException {
		LogUtil.info("==========开始打包嘉银自然人身份证文件信息==========");
		Date startDate = null;
		Date endDate = null;
		if (start != null) {
			startDate = new Date(start);
		} else {
			startDate = new Date(0);
		}
		if (end != null) {
			endDate = new Date(end);
		} else {
			endDate = new Date();
		}
		List<ExportJiaYinNaturalPersonDto> naturalPersonDtoList = crowdsourceMapper.queryJiaYinNaturalPerson(startDate, endDate);
		if (null != naturalPersonDtoList && naturalPersonDtoList.size() > 0) {
			LogUtil.info("嘉银现在拥有项目的自然人共有：" + naturalPersonDtoList.size() + "人！");
			//新建一个临时文件夹，将后续所有文件夹都放在这个文件夹下
			String temporaryFolderName = "temporaryFolder" + System.currentTimeMillis();
			File temporaryFolderFile = new File("/usr/local/" + temporaryFolderName);
			if (!temporaryFolderFile.exists()) {
				if (!temporaryFolderFile.mkdirs()) {
					LogUtil.error("新建总的临时文件夹失败！");
					return;
				}
			}
			for (ExportJiaYinNaturalPersonDto dto : naturalPersonDtoList) {
				//新建文件夹存放身份证图片信息
				String folderFileName = dto.getName() + "+" + dto.getIdNo();
				File folderFile = new File("/usr/local/" + temporaryFolderName + "/" + folderFileName);
				if (!folderFile.exists()) {
					if (!folderFile.mkdirs()) {
						LogUtil.error("新建存放身份证图片的文件夹失败！文件夹名称：" + folderFileName);
						continue;
					}
				}
				//复制身份证文件
				copyIdNoFile(dto.getCrowdsourceid(), temporaryFolderName, folderFileName);
			}
			LogUtil.info("======================打包结束======================");
			LogUtil.info("====================开始压缩文件====================");
			OutputStream out = response.getOutputStream();
			try {
				if (1 == type) {
					// 调用方法打包zip文件
					byte[] data = FileUtil.createZip(temporaryFolderFile.getPath());
					// 压缩包名称
					String downloadName = "嘉银拥有项目的自然人身份证文件信息.zip";
					response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadName, "utf-8"));
					response.addHeader("Content-Length", "" + data.length);
					response.setContentType("application/octet-stream;charset=UTF-8");
					IOUtils.write(data, out);
				} else {
					String ossPath = uploadPathConfig.getUploadpath();
					String path = "compressPackage/" + DateUtil.DateToStr("yyyyMMdd", new Date());
					String fileName = "压缩包.zip";
					FileUtil.createZipFile(temporaryFolderFile.getPath(), ossPath, path, fileName);
				}
			} catch (Exception e) {
				LogUtil.error("将文件夹压缩为压缩包失败！");
			} finally {
				try {
					// 压缩成功后删除项目中文件夹
					if (temporaryFolderFile.exists()) {
						FileUtil.delFiles(temporaryFolderFile);
					}
					if (out != null) {
						out.flush();
						out.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
					LogUtil.error("将文件夹压缩为压缩包出现异常！");
				}
			}
			LogUtil.info("====================压缩文件结束====================");
		} else {
			LogUtil.info("导出嘉银自然人-没有查询到嘉银自然人！");
		}
	}

	public void compressIdNoFileById(HttpServletResponse response, int[] ids) throws IOException {
		if (null == ids) {
			LogUtil.error("根据自然人ID压缩身份证文件-参数错误！");
			return;
		}
		//新建一个临时文件夹，将后续所有文件夹都放在这个文件夹下
		String temporaryFolderName = "temporaryFolder" + System.currentTimeMillis();
		File temporaryFolderFile = new File("/usr/local/" + temporaryFolderName);
		if (!temporaryFolderFile.exists()) {
			if (!temporaryFolderFile.mkdirs()) {
				LogUtil.error("新建总的临时文件夹失败！");
				return;
			}
		}
		for (int id : ids) {
			//查询自然人
			CrowdsourceAccount crowdsourceAccount = new CrowdsourceAccount().selectOne(Condition.create().eq("crowdsourceid", id));
			if (null == crowdsourceAccount) {
				LogUtil.error("根据自然人ID压缩身份证文件-没有查询到自然人！ID：" + id);
				continue;
			}
			//新建文件夹存放身份证图片信息
			String folderFileName = crowdsourceAccount.getRealname() + "+" + crowdsourceAccount.getIdno();
			File folderFile = new File("/usr/local/" + temporaryFolderName + "/" + folderFileName);
			if (!folderFile.exists()) {
				if (!folderFile.mkdirs()) {
					LogUtil.error("新建存放身份证图片的文件夹失败！文件夹名称：" + folderFileName);
					continue;
				}
			}
			//复制身份证文件
			copyIdNoFile(id, temporaryFolderName, folderFileName);
		}
		LogUtil.info("====================开始压缩文件====================");
		OutputStream out = response.getOutputStream();
		try {
			// 调用方法打包zip文件
			byte[] data = FileUtil.createZip(temporaryFolderFile.getPath());
			// 压缩包名称
			String downloadName = "自然人身份文件信息.zip";
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadName, "utf-8"));
			response.addHeader("Content-Length", "" + data.length);
			response.setContentType("application/octet-stream;charset=UTF-8");
			IOUtils.write(data, out);
		} catch (Exception e) {
			LogUtil.error("将文件夹压缩为压缩包失败！");
		} finally {
			try {
				// 压缩成功后删除项目中文件夹
				if (temporaryFolderFile.exists()) {
					FileUtil.delFiles(temporaryFolderFile);
				}
				if (out != null) {
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				LogUtil.error("根据自然人ID压缩身份证文件-将文件夹压缩为压缩包出现异常！");
			}
		}
		LogUtil.info("====================压缩文件结束====================");
	}

	public SmartResult compressIdNoInfo(BaseSimpleFormBean<Integer> formBean) {
		if (null == formBean || null == formBean.getReqdata()) {
			return errorParamSmartResult();
		}
		mergeInvoiceIdNoInfoCompress(formBean.getReqdata());
		return smartResult();
	}

	/**
	 * 压缩合并开票下自然人身份证文件
	 *
	 * @param id
	 */
	public void mergeInvoiceIdNoInfoCompress(int id) {
		//查询合并开票信息
		ForeignInvoice foreignInvoice = new ForeignInvoice().selectById(id);
		if (null != foreignInvoice) {
			//查询合并开票的开票信息
			List<ForeignInvoice> invoiceList = new ForeignInvoice().selectList(Condition.create().eq("merge_id", id));
			if (null != invoiceList && invoiceList.size() > 0) {
				LogUtil.info("==========开始创建合并开票" + id + "下自然人身份证文件==========");
				//新建一个临时文件夹，将后续所有文件夹都放在这个文件夹下
				String temporaryFolderName = "temporaryFolder" + System.currentTimeMillis();
				File temporaryFolderFile = new File("/usr/local/" + temporaryFolderName);
				if (!temporaryFolderFile.exists()) {
					if (!temporaryFolderFile.mkdirs()) {
						LogUtil.error("压缩合并开票下自然人身份证文件-新建总的临时文件夹失败！");
						return;
					}
				}
				for (ForeignInvoice invoice : invoiceList) {
					//查询自然人信息
					CrowdsourceAccount account = new CrowdsourceAccount().selectOne(
							Condition.create().eq("crowdsourceid", invoice.getCrowdsourceid()));
					if (null != account) {
						//新建文件夹存放身份证图片信息
						String folderFileName = account.getRealname() + "+" + account.getIdno();
						File folderFile = new File("/usr/local/" + temporaryFolderName + "/" + folderFileName);
						if (!folderFile.exists()) {
							if (!folderFile.mkdirs()) {
								LogUtil.error("压缩合并开票下自然人身份证文件-新建存放身份证图片的文件夹失败！文件夹名称：" + folderFileName);
								continue;
							}
						}
						//复制身份证文件
						copyIdNoFile(account.getCrowdsourceid(), temporaryFolderName, folderFileName);
					} else {
						LogUtil.error("压缩合并开票下自然人身份证文件-没有查询到自然人信息！自然人ID：" + invoice.getCrowdsourceid());
					}
				}
				LogUtil.info("==========创建结束==========");
				LogUtil.info("==========开始压缩==========");
				//oss路径
				String ossPath = uploadPathConfig.getUploadpath();
				//路径
				String path = "compressPackage/" + DateUtil.DateToStr("yyyyMMdd", new Date());
				//构建压缩包名称
				String fileName = foreignInvoice.getProjectServiceName() + "下自然人身份文件" + foreignInvoice.getId() + ".zip";
				//压缩包存放路径
				String filePath = "";
				try {
					// 调用方法打包zip文件
					filePath = FileUtil.createZipFile(temporaryFolderFile.getPath(), ossPath, path, fileName);
				} catch (Exception e) {
					LogUtil.error("压缩合并开票下自然人身份证文件-将文件夹压缩为压缩包失败！生成时间：" + DateUtil.DateToStr("yyyy-MM-dd HH:mm", new Date()));
				} finally {
					// 压缩成功后删除项目中文件夹
					if (temporaryFolderFile.exists()) {
						FileUtil.delFiles(temporaryFolderFile);
					}
				}
				if (StringUtil.isEmpty(filePath)) {
					foreignInvoice.setEnclosureInfo("附件生成失败！").setGeneratetime(new Date()).updateById();
				} else {
					foreignInvoice.setEnclosureInfo("/" + filePath).setGeneratetime(new Date()).updateById();
				}
				LogUtil.info("==========压缩结束==========");
			} else {
				LogUtil.error("压缩合并开票下自然人身份证文件-没有查询到合并开票下的开票信息！ID：" + id);
			}
		} else {
			LogUtil.error("压缩合并开票下自然人身份证文件-没有查询到合并开票信息！ID：" + id);
		}
	}

	public void copyIdNoFile(int crowdsourceid, String temporaryFolderName, String folderFileName) {
		//获取身份证正面信息
		CrowdsourceFile crowdsourceFile1 = new CrowdsourceFile().selectOne(
				Condition.create().eq("crowdsourceid", crowdsourceid).eq("file_type", 1));
		if (null != crowdsourceFile1) {
			File positive = new File("/usr/local/oss/zdd-img/" + crowdsourceFile1.getFilePath());
			//获取文件名
			String fileName = crowdsourceFile1.getFilePath().substring(crowdsourceFile1.getFilePath().lastIndexOf("/"));
			//new一个空的File用来复制
			File copyPositive = new File("/usr/local/" + temporaryFolderName + "/" + folderFileName + fileName);
			try {
				Files.copy(positive.toPath(), copyPositive.toPath());
			} catch (Exception e) {
				LogUtil.error("身份证人像面复制失败！自然人ID：" + crowdsourceid);
			}
		} else {
			LogUtil.error("自然人没有身份证人像面图片！自然人ID：" + crowdsourceid);
		}
		//获取身份证反面信息
		CrowdsourceFile crowdsourceFile2 = new CrowdsourceFile().selectOne(
				Condition.create().eq("crowdsourceid", crowdsourceid).eq("file_type", 2));
		if (null != crowdsourceFile2) {
			File back = new File("/usr/local/oss/zdd-img/" + crowdsourceFile2.getFilePath());
			//获取文件名
			String fileName = crowdsourceFile2.getFilePath().substring(crowdsourceFile2.getFilePath().lastIndexOf("/"));
			//new一个空的File用来复制
			File copyBack = new File("/usr/local/" + temporaryFolderName + "/" + folderFileName + fileName);
			try {
				Files.copy(back.toPath(), copyBack.toPath());
			} catch (Exception e) {
				LogUtil.error("身份证国徽面复制失败！自然人ID：" + crowdsourceid);
			}
		} else {
			LogUtil.error("自然人没有身份证国徽面图片！自然人ID：" + crowdsourceid);
		}
	}

	/**
	 * 推送结算单
	 *
	 * @param formBean 参数
	 * @return success
	 */
	private SmartResult settlementElectronicReceipt(BaseSimpleFormBean<CompleteInvoiceFormBean> formBean) {
		CompleteInvoiceFormBean completeInvoiceFormBean = formBean.getReqdata();
		if (StringUtil.isEmpty(completeInvoiceFormBean.getElectronicReceipt())) {
			return errorParamSmartResult();
		}
		CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectOne(Condition.create()
				.eq("projectid", completeInvoiceFormBean.getProjectId())
				.eq("crowdsourceid", completeInvoiceFormBean.getCrowdsourceid()));
		if (null == crowdsourceInvoice) {
			return smartResult(StatusMsg.StatusMsg_617);
		}
		try {
			//结算单文件
			File electronicReceipt = new File(uploadPathConfig.getUploadpath() + completeInvoiceFormBean.getElectronicReceipt());
			String fileNames = electronicReceipt.getName();
			//获取文件名称 /confirm/20201102/2ae6d03b-c7aa-4989-aa92-bf3d870398ee.MOV
			String fileName = fileNames.substring(0, fileNames.lastIndexOf("."));
			//文件路径+名字
			String folder = completeInvoiceFormBean.getElectronicReceipt()
					.substring(0, completeInvoiceFormBean.getElectronicReceipt().lastIndexOf("."));
			//pdf名称
			String target = uploadPathConfig.getUploadpath() + folder + "pdf版.pdf";
			//图片转pdf
			DocUtils.imageConvertPdf(uploadPathConfig.getUploadpath() + completeInvoiceFormBean.getElectronicReceipt(), target);
			//pdf转base64
			String wordInfo = Base64.encodeBase64File(target);

			UploadSettlementSheetFormBean uploadSettlementSheetFormBean = new UploadSettlementSheetFormBean();
			uploadSettlementSheetFormBean.setFILEBASE(wordInfo)
					.setPLATSRL(crowdsourceInvoice.getPlatstr())
					.setFILETYPE("pdf")
					.setFILENAME(fileName + "pdf版");
			BaseSimpleFormBean<UploadSettlementSheetFormBean> formBean1 = new BaseSimpleFormBean<>();
			formBean1.setReqdata(uploadSettlementSheetFormBean);
			RestTemplate restTemplate = new RestTemplate();
			return restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getUploadSettlementSheet(), formBean1,
					SmartResult.class);
		} catch (Exception e) {
			e.printStackTrace();
			return smartResult(StatusMsg.StatusMsg_199);
		}
	}

	/**
	 * 上传结算发票
	 *
	 * @param formBean
	 * @return
	 */
	private SmartResult settlementInvoicePicture(BaseSimpleFormBean<CompleteInvoiceFormBean> formBean) {
		CompleteInvoiceFormBean completeInvoiceFormBean = formBean.getReqdata();
		if (StringUtil.isAnyEmpty(completeInvoiceFormBean.getInvoiceFaceNumber(), completeInvoiceFormBean.getInvoicePicture())) {
			return errorParamSmartResult();
		}
		CrowdsourceInvoice crowdsourceInvoice = new CrowdsourceInvoice().selectOne(Condition.create()
				.eq("projectid", completeInvoiceFormBean.getProjectId())
				.eq("crowdsourceid", completeInvoiceFormBean.getCrowdsourceid()));
		if (null == crowdsourceInvoice) {
			return smartResult(StatusMsg.StatusMsg_617);
		}
		try {
			//结算发票文件
			File invoicePicture = new File(uploadPathConfig.getUploadpath() + completeInvoiceFormBean.getInvoicePicture());
			String fileNames = invoicePicture.getName();
			//获取文件名称
			String fileName = fileNames.substring(0, fileNames.lastIndexOf("."));
			//开票时间
			String date = DateUtil.DateToStr("yyyy-MM-dd", formBean.getReqdata().getKPDATE());
			UploadSettlementInvoiceFormBean uploadSettlementInvoiceFormBean = new UploadSettlementInvoiceFormBean();
			uploadSettlementInvoiceFormBean.setFILEBASE(ImgBase64Util.ImgToBase64(invoicePicture.getAbsolutePath()))
					.setPLATSRL(crowdsourceInvoice.getPlatstr())
					.setFILETYPE("png")
					.setFILENAME(fileName)
					.setKPDATE(date)
					.setINVOICENUMBER(completeInvoiceFormBean.getInvoiceFaceNumber());

			BaseSimpleFormBean<UploadSettlementInvoiceFormBean> formBean1 = new BaseSimpleFormBean<>();
			formBean1.setReqdata(uploadSettlementInvoiceFormBean);
			RestTemplate restTemplate = new RestTemplate();
			return restTemplate.postForObject(zddUrlConfig.getYunkongUrl() + yunKongConfig.getUploadSettlementInvoice(), formBean1,
					SmartResult.class);
		} catch (Exception e) {
			e.printStackTrace();
			return smartResult(StatusMsg.StatusMsg_199);
		}
	}

	public void exportReceivable(HttpServletResponse response, Date startDate, Date endDate) {
		//获取模板路径
		String templatePath = kingdeeTemplateConfig.getReceivableTemplatePath();
		List<ExportReceivableDto> dtoList = new ArrayList<>();
		List<ReceivableDto> receivableDtoList = crowdsourceProjectMapper.queryReceivableDto(startDate, endDate);
		if (null != receivableDtoList && receivableDtoList.size() > 0) {
			//序号默认从100000开始
			int number = 100000;
			//金额格式化
			DecimalFormat df = new DecimalFormat("##,##0.00");
			for (ReceivableDto dto : receivableDtoList) {
				number = number + 1;
				//项目税费
				String projectTaxAmount = df.format(dto.getProjectTaxAmount());
				//项目金额
				String projectAmount = df.format(dto.getProjectAmount());
				//实际成交金额
				String transactionAmount = df.format(dto.getTransactionAmount());
				//项目开始时间
				String date = DateUtil.DateToStr("yyyy-MM-dd", dto.getCreatetime());

				//金蝶：结算组织  按项目发布时间获取该企业该时间之前的的充值最近一笔的充值主体账号
				ReceiptDto receiptDto = companyRechargeMapper.queryLastReceiptDto(dto.getCompanyId(), dto.getCreatetime());
				if (receiptDto != null && !StringUtils.isEmpty(receiptDto.getSubjectCompanyName())) {
					dto.setSubjectCompanyName(receiptDto.getSubjectCompanyName());
					dto.setSubjectCompanyOrganizationCode(receiptDto.getSubjectCompanyOrganizationCode());
				}

				ExportReceivableDto exportReceivableDto = ExportReceivableDto.of(number, date, projectTaxAmount, projectAmount,
						transactionAmount, dto);
				dtoList.add(exportReceivableDto);
			}
		}
		String fileName = "附件二：应收单" + DateUtil.DateToStr("yyyy-MM-dd", new Date());
		try {
			EasyExcelUtil.exportComplex(response, templatePath, fileName, dtoList);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("导出应收单失败");
		}
	}

	/**
	 * 刷新智众包项目的整体支付情况,比如 成功多少条,失败多条,成功支付多少钱,失败支付多少钱等.
	 *
	 * @param tradeRecord
	 * @param project
	 */
	private void refreshCrowdsourceProjectState(CrowdsourceTradeRecord tradeRecord, CrowdsourceProject project) {
		List<CrowdsourceTradeRecordItem> itemList = new CrowdsourceTradeRecordItem().selectList(
				Condition.create().eq("projectid", tradeRecord.getProjectid()).eq("repay", 0));
		if (CollectionUtils.isEmpty(itemList)) return;

		int succCount = 0;
		int failCount = 0;
		BigDecimal succAmount = BigDecimal.ZERO;
		BigDecimal failAmount = BigDecimal.ZERO;
		for (CrowdsourceTradeRecordItem item : itemList) {
			Integer status = item.getStatus();
			if (status == Constants.CROWDSOURCE_BATCH_ITEM_PAID) {
				succCount++;
				succAmount = succAmount.add(item.getTradeamount());
			} else {
				failCount++;
				failAmount = failAmount.add(item.getTradeamount());
			}
		}

		tradeRecord.setTotalSuccCount(succCount).setTotalSuccAmount(succAmount).setTotalFailCount(failCount).setTotalFailAmount(failAmount);

		if (succCount > itemList.size()) {
			project.setState(Constants.CROWDSOURCE_PROJECT_ALL_PAID_EX);
		} else if (succCount == itemList.size()) {
			project.setState(Constants.CROWDSOURCE_PROJECT_ALL_PAID).setFinishtime(new Date());
			handleCrowdsourceProjectMatch(project);
			coreBrokerageService.handleCrowdsourceProjectPartnerBrokerage(tradeRecord, project);
		} else if (succCount > 0) {
			project.setState(Constants.CROWDSOURCE_PROJECT_PART_PAID);
		} else {
			project.setState(Constants.CROWDSOURCE_PROJECT_PAYING);
		}
	}

	/**
	 * 如果是撮合类型的项目, 初始化撮合项目
	 *
	 * @param project
	 */
	private void handleCrowdsourceProjectMatch(CrowdsourceProject project) {
		if (project == null || project.getProjectType() != CrowdsourceProjectType.MATCH) return;
		CrowdsourceProjectMatch projectMatch = crowdsourceProjectMatchMapper.getByProjectid(project.getProjectid());
		if (projectMatch != null) return;
		new CrowdsourceProjectMatch().setCompid(project.getCompid())
				.setProjectid(project.getProjectid())
				.setState(CrowdsourceProjectMatchState.CREATED)
				.insert();
	}

	private void refreshCrowdsourceTradeRecordStatus(CrowdsourceTradeRecord tradeRecord, CrowdsourceProject crowdsourceProject) {
		Integer state = crowdsourceProject.getState();
		switch (state) {
			case Constants.CROWDSOURCE_PROJECT_CREATE:
				tradeRecord.setBatchStatus(Constants.CROWDSOURE_BATCH_TRADE_SUBMITTED);
				break;
			case Constants.CROWDSOURCE_PROJECT_PAYING:
			case Constants.CROWDSOURCE_PROJECT_PART_PAID:
				tradeRecord.setBatchStatus(Constants.CROWDSOURE_BATCH_TRADE_BATCH_HANDLING);
				break;
			case Constants.CROWDSOURCE_PROJECT_ALL_PAID:
			case Constants.CROWDSOURCE_PROJECT_ALL_PAID_EX:
				tradeRecord.setBatchStatus(Constants.CROWDSOURE_BATCH_TRADE_BATCH_FINISHED).setFinishtime(new Date());
				break;
			case Constants.CROWDSOURCE_PROJECT_FAILED:
			case Constants.CROWDSOURCE_PROJECT_CANCELLED:
				tradeRecord.setBatchStatus(Constants.CROWDSOURE_BATCH_TRADE_BATCH_FAILED).setFinishtime(new Date());
				break;
			default:

				break;
		}
	}

	public SmartResult openConvertZddMaker(BaseSimpleFormBean<Integer> formBean) {
		@Valid Integer userid = formBean.getReqdata();
		StudioDetailDto studioDetail = makerStudioMapper.getStudioDetail(userid);
		Asserts.notNull(studioDetail, StatusMsg.StatusMsg_601);
		Asserts.isTrue(NumberUtil.equals(studioDetail.getMakerType(), MakerType.CROWDSOURCE), StatusMsg.StatusMsg_601);
		new MakerStudio().setUserid(userid).setCrowdsourceConvertZddMaker(Constants.TRUE).updateById();
		return SmartResult.success();
	}

	/**
	 * 上传众包任务证据链
	 *
	 * @param formBean formBean
	 * @return success
	 */
	@Transactional
	public SmartResult uploadProjectFileUrl(BaseSimpleFormBean<UploadProjectFileUrlFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || CollectionUtils.isEmpty(formBean.getReqdata().getProjectIds())) {
			return errorParamSmartResult();
		}
		UploadProjectFileUrlFormBean reqdata = formBean.getReqdata();
		List<CrowdsourceProject> crowdsourceProjectList = new CrowdsourceProject().selectList(Condition.create().in("projectid", reqdata.getProjectIds()));
		if (CollectionUtils.isEmpty(crowdsourceProjectList)) {
			return smartResult(StatusMsg.StatusMsg_606);
		}
		for(CrowdsourceProject crowdsourceProject:crowdsourceProjectList) {
			crowdsourceProject.setProjectFileUrl(reqdata.getProjectFileUrl());
			//保存备注
			crowdsourceProject.setRemarksField(reqdata.getRemarksField());
			if (!crowdsourceProject.updateById()) {
				throw new SmartException(StatusMsg.StatusMsg_199);
			}
		}
		return smartResult();
	}
	//查询近期帐单
	public SmartResult RechargeReceipt(Integer projectid){
		if (projectid == null || projectid<= 0) return errorParamSmartResult();
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectOne(Condition.create().eq("projectid", projectid));
		int compid=crowdsourceProject.getCompid();
		Date createtime=crowdsourceProject.getCreatetime();
		RechargeReceiptDto receipt = companyMapper.getRechargeReceipt(compid,createtime);
		if (receipt == null) return emptyDataSmartResult();
		return smartResult(receipt);
	}

	public SmartResult<CrowdsourceProjectDeliveryFileDto> listProjectDeliveryFiles(BaseSimpleFormBean<Integer> formBean) {
		Integer projectid = formBean.getReqdata();
		CrowdsourceProject project = crowdsourceProjectMapper.selectById(projectid);
		if (StringUtil.isNotEmpty(project.getDeliveryPath())) {
			CrowdsourceProjectDeliveryFileDto dto = new CrowdsourceProjectDeliveryFileDto().setProjectid(projectid)
					.setDeliveryPath(project.getDeliveryPath());
			return SmartResult.success(Lists.newArrayList(dto));
		} else {
			List<CrowdsourceProjectDeliveryFileDto> list = crowdsourceProjectItemMapper.listProjectDeliveryFiles(projectid);
			return SmartResult.success(list);
		}
	}

	/**
	 * 针对已验收的项目生成为交付物
	 * @param acceptance
	 * @return
	 */
	public SmartResult generateProjectDeliveryFile(GenerateProjectAcceptance acceptance){
		Asserts.notEmpty(acceptance.getProjectIds(),StatusMsg.StatusMsg_136);

		Asserts.notNull(NumberUtil.intIn(acceptance.getTemplateType(), 2, 3));
		List<ExportProjectAcceptanceDto> dtos = docService.generateCrowdsourceDocDeliverFile(0, acceptance.getProjectIds(), acceptance.getTemplateType(), true);
		Set<String> projectIds = dtos.stream().map(t->t.getProjectid().toString()).collect(Collectors.toSet());

		if(StringUtils.isNotBlank(acceptance.getProjectIds())) {
			if(CollectionUtils.isEmpty(dtos)){
				return SmartResult.fail(StatusMsg.StatusMsg_142);
			}
			String[] originalIds = acceptance.getProjectIds().split(",");
			if (projectIds.size() != originalIds.length) {
				Set<String> originalList = new HashSet<>(Arrays.asList(originalIds));
				originalList.removeAll(projectIds);
				return SmartResult.success(originalList);
			}
		}
		return SmartResult.success();
	}
	//子项目证据链上传
	@Transactional
	public SmartResult subprojectEvidenceChain(BaseSimpleFormBean<UploadProjectFileUrlFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || CollectionUtils.isEmpty(formBean.getReqdata().getProjectIds())) {
			return errorParamSmartResult();
		}
		UploadProjectFileUrlFormBean reqdata = formBean.getReqdata();
		List<CrowdsourceProjectItem> crowdsourceProjectItems = new CrowdsourceProjectItem().selectList(Condition.create().in("projectid", reqdata.getProjectIds()));
		if (CollectionUtils.isEmpty(crowdsourceProjectItems)) {
			return smartResult(StatusMsg.StatusMsg_606);
		}
		for(CrowdsourceProjectItem crowdsourceProjectItem:crowdsourceProjectItems) {
			crowdsourceProjectItem.setProjectFileUrl(reqdata.getProjectFileUrl());
			if (!crowdsourceProjectItem.updateById()) {
				throw new SmartException(StatusMsg.StatusMsg_199);
			}
		}
		return smartResult();
	}


	public SmartResult<TaxPaymentVoucherListDto> taxPaymentVoucherList(BaseSimpleFormBean<TaxPaymentVoucherListFormBean> formBean) {
		Page<TaxPaymentVoucherListDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<TaxPaymentVoucherListDto> list = taxPaymentVoucherMapper
				.taxPaymentVoucherList(formBean.getReqdata().getTaxSourceId(),formBean.getReqdata().getOperatingEntityId());
 		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public SmartResult addTaxPaymentVoucher(TaxPaymentVoucher formBean) {
		if (formBean.getId() == 0){
			formBean.insert();
			return smartResult();
		}

		TaxPaymentVoucher taxPaymentVoucher = taxPaymentVoucherMapper.selectById(formBean.getId());
		if (taxPaymentVoucher == null){
			return smartResult(StatusMsg.StatusMsg_102);
		}
		formBean.updateById();
		return smartResult();
	}

	public SmartResult<TaxPaymentVoucherListDto> taxPaymentVoucherDetails(Integer formBean) {
		return smartResult(taxPaymentVoucherMapper.taxPaymentVoucherDetails(formBean));
	}

	public SmartResult deleteTaxPaymentVoucher(Integer formBean) {
		TaxPaymentVoucher taxPaymentVoucher = taxPaymentVoucherMapper.selectById(formBean);
		if (taxPaymentVoucher == null){
			return smartResult(StatusMsg.StatusMsg_102);
		}
		taxPaymentVoucher.setIsDelete(1).updateById();
		return smartResult();
	}

	/**
	 * 个人资金流水
	 */
	public SmartResult personalCapitalFlow(BaseSimpleFormBean<PersonalCapitalFlowFormBean> formBean) {
		PersonalCapitalFlowFormBean reqdata = formBean.getReqdata();
		//时间处理
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();
		Page<PersonalCapitalFlowDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<PersonalCapitalFlowDto> list = crowdsourceTradeRecordItemMapper
				.personalCapitalFlow(reqdata.getNameOfPayee(),reqdata.getTransactionStatus(),
						reqdata.getMerchantName(),reqdata.getItemType(),
						reqdata.getWhetherToSupplement(),reqdata.getTaxSourceId(),
						startDate,endDate);
		list.stream().forEach(dto->{
			GetPhoneDto getPhoneDto;
			if (dto.getUserType() == 1){
				getPhoneDto = crowdsourceMapper.getPhone(dto.getUserid());
			}else{
				getPhoneDto = makerAccountMapper.getPhone(dto.getUserid());
			}
			dto.setDocumentNumber(getPhoneDto.getIdno());
			dto.setMobile(getPhoneDto.getPhone());
			dto.setServiceCharge(dto.getTradeAmount().multiply(dto.getTaxSourceCostRate()));
		});
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public void derivePersonalCapitalFlow( HttpServletResponse response,PersonalCapitalFlowFormBean reqdata) {
		//时间处理
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();
		List<PersonalCapitalFlowDto> list = crowdsourceTradeRecordItemMapper
				.personalCapitalFlow(reqdata.getNameOfPayee(),reqdata.getTransactionStatus(),
						reqdata.getMerchantName(),reqdata.getItemType(),
						reqdata.getWhetherToSupplement(),reqdata.getTaxSourceId(),
						startDate,endDate);
		list.stream().forEach(dto->{
			GetPhoneDto getPhoneDto;
			if (dto.getUserType() == 1){
				getPhoneDto = crowdsourceMapper.getPhone(dto.getUserid());
			}else{
				getPhoneDto = makerAccountMapper.getPhone(dto.getUserid());
			}
			dto.setDocumentNumber(getPhoneDto.getIdno());
			dto.setMobile(getPhoneDto.getPhone());
			dto.setServiceCharge(dto.getTradeAmount().multiply(dto.getTaxSourceCostRate()));
		});
		String file = RandomUtil.createRandomNo("导出个人资金流水", "");
		try {
			EasyExcel.write(getExcelOutPutStream(response, file), PersonalCapitalFlowDto.class).sheet("导出个人资金流水").doWrite(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 智零工业务发票列表
	 * @param formBean
	 * @return
	 */
	public SmartResult smartGigBusinessInvoiceList(BaseSimpleFormBean<QueryContractorInvoiceFormBean> formBean){
		QueryContractorInvoiceFormBean reqdata = formBean.getReqdata();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		if (startDate == null) {
			startDate = new Date(0);
		}
		if (endDate == null) {
			endDate = new Date();
		}
		Page<ContractorInvoicefDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<ContractorInvoicefDto> list = contractorInvoiceMapper.smartGigBusinessInvoiceList(reqdata.getCompanyName(),
				reqdata.getState(),startDate,
				endDate,reqdata.getItemType(),reqdata.getWhetherToSupplement(),reqdata.getTaxSourceId());
		return smartResultPage(page);
	}

	/**
	 * 上传发票
	 * @param formBean
	 * @return
	 */
	public SmartResult uploadInvoice(BaseSimpleFormBean<EditContractorInvoiceFormBean> formBean) {
		EditContractorInvoiceFormBean reqdata = formBean.getReqdata();
		ContractorInvoice invoice = new ContractorInvoice().selectById(reqdata.getInvoiceId());
		CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(invoice.getProjectid());
		if(invoice == null || crowdsourceProject == null){
			return smartResult(StatusMsg.StatusMsg_326);
		}
		invoice.setPartyId(crowdsourceProject.getPartyId())
				.setInvoiceCityId(crowdsourceProject.getTaxSourceId())
				.setState(Constants.CROWDSOURCE_INVOICE_STATE_3)
				.setInvoicePicture(reqdata.getInvoicePicture())
				.setRemarks(reqdata.getRemarks())
				.setOperator(formBean.getUserid())
				.setFinishtime(new Date())
				.setInvoicedAmount(crowdsourceProject.getProjectTotalAmount())
				.updateById();
		return smartResult();
	}
	/**
	 * 智零工业务发票列表
	 * @param formBean
	 * @return
	 */
	public SmartResult invoiceDetails(BaseSimpleFormBean<EditContractorInvoiceFormBean> formBean){
		return smartResult(contractorInvoiceMapper.invoiceDetails(formBean.getReqdata().getInvoiceId()));
	}

	public void deriveSmartGigBusinessInvoice( HttpServletResponse response,QueryContractorInvoiceFormBean reqdata) {
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		if (startDate == null) {
			startDate = new Date(0);
		}
		if (endDate == null) {
			endDate = new Date();
		}
		List<InvoiceDetailsDto> list = contractorInvoiceMapper.deriveSmartGigBusinessInvoice(reqdata.getCompanyName(),
				reqdata.getState(),startDate,
				endDate,reqdata.getItemType(),reqdata.getWhetherToSupplement(),reqdata.getTaxSourceId());
		String file = RandomUtil.createRandomNo("导出智零工业务发票列表", "");
		try {
			EasyExcel.write(getExcelOutPutStream(response, file), InvoiceDetailsDto.class).sheet("导出智零工业务发票列表").doWrite(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导入联系人
	 */
	@Transactional
	public SmartResult uploadCrowdsource(MultipartFile file, int compid,int createBy) {
		if(file == null || file.isEmpty()){
			return smartResult(StatusMsg.StatusMsg_199);
		}
		//保留原文件
		String filePath = FileUtil.uploadFileOwnName(uploadPathConfig.getUploadpath(), file);

		CompanyDetailDto company = companyMapper.getCompanyInfo(compid);
		if (company == null || company.getState() != Constants.comp_state_4) return smartResult(StatusMsg.StatusMsg_313);
		try {
			//读取文件
			UploadCrowdsourceListener listener = new UploadCrowdsourceListener(company,crowdsourceAccountMapper);
			EasyExcel.read(file.getInputStream(), UploadCrowdsourceFormBean.class, listener).sheet().headRowNumber(2).doRead();
			if(listener.getSmartResult().isSuccessful()){
				// 新增导入自然人文件记录
				new CrowdsourceImportRecord().setCompid(compid)
											 .setFilePath(filePath)
											 .setCreateBy(createBy)
											 .setImportNum(listener.getInsertIds().size())
											 .setImportCrowdsourceIds(StringUtils.join(listener.getInsertIds(),","))
											 .insert();
			}
			return listener.getSmartResult();
		} catch (Exception e) {
			log.error("导入自然人失败", e);
			//手动回滚
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return SmartResult.fail(StatusMsg.StatusMsg_135, e.getMessage());
		}
	}

	public SmartResult getCrowdsourceUploadRecord(BaseSimpleFormBean<CrowdsourceImportRecordFormBean> formBean) {
		CrowdsourceImportRecordFormBean req = formBean.getReqdata();
		Page<CrowdsourceImportRecord> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		crowdsourceImportRecordMapper.getList(req.getCompname(), req.getCreateBy(), req.getCreateStart(), req.getCreateEnd());
		return smartResultPage(page);
	}

	/**
	 * 导入并创建众包项目
	 * @param file
	 * @param formBean
	 * @return
	 */
	@Transactional
	public SmartResult importCreateCrowdsourceProject(MultipartFile file, ImportCrowdProjectFormBean formBean) {
		if(file == null || file.isEmpty()){
			return smartResult(StatusMsg.StatusMsg_134);
		}
		int compid = formBean.getCompid();
		Company company = companyMapper.selectById(compid);
		if (company == null || company.getState() != Constants.comp_state_4) {
			return smartResult(StatusMsg.StatusMsg_313);
		}
		if(formBean.getWorkType() == Constants.WORK_TYPE_2 && company.getOpenOddJob() != 1) {
				return smartResult(StatusMsg.StatusMsg_378);
		}
		if (formBean.getWorkType() == Constants.WORK_TYPE_1 && company.getIntelCrowdsource() != 2) {
			return smartResult(StatusMsg.StatusMsg_352);
		}

		Integer projectType = formBean.getProjectType();
		if (NumberUtil.equals(company.getCrowdsourceProjectMatch(), 1) && NumberUtil.equals(projectType, CrowdsourceProjectType.MATCH)) {
			return smartResult(StatusMsg.StatusMsg_337);
		}

		// 获取企业默认支付方式
		CompanyParty companyParty = coreCompanyService.getCompanyDefaultPartyMul(compid, formBean.getWorkType());
		if (companyParty == null) return smartResult(StatusMsg.StatusMsg_384);

		//查询税源地税率
		BigDecimal taxSourceCostRate = taxSourceMapper.getRateByTaxSourceId(companyParty.getTaxSourceId());

		//保留原文件
		String filePath = FileUtil.uploadFileOwnName(uploadPathConfig.getUploadpath(), file);
		//文件名称
		String fileName = file.getOriginalFilename();
		//检查文件名是否已存在
		if (formBean.isCheckFileExist() && projectFileService.onTheDayCheckFileExist(ProjectType.CROWDSOURCE, compid, fileName)) {
			throw SmartException.of(StatusMsg.StatusMsg_147);
		}
		//存储文件
		Integer fileRecordId = projectFileService.insertFileName(ProjectType.CROWDSOURCE, compid, fileName, filePath);
		try {
			double partnerBrokerageRate = crowdsourceProjectService.getPartnerBrokerageRate(compid);
			//企业设置的城市的限额
			CrowdsourceCityQuota personalQuota = crowdsourceProjectService.findPersonalCityQuota(companyParty.getCityId());
			//读取文件

			CrowdsourceProjectUploadListener listener = new CrowdsourceProjectUploadListener(company, companyParty, personalQuota, projectType, fileRecordId, formBean.getWorkType(),formBean.getCreateBy(),
					taxSourceCostRate, partnerBrokerageRate, crowdsourceProjectService, coreSensitiveService, makerMapper);
			EasyExcel.read(file.getInputStream(), ImportCrowdsourceProjectFormBean.class, listener).sheet(0).headRowNumber(6).doRead();
			if (listener.getSmartResult().isFailed()) {
				// 回滚存储文件
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
			return listener.getSmartResult();
		} catch (SmartException | IOException e) {
			log.error("importCreateCrowdsourceProject 导入众包文件解析失败：{}", e.getMessage());
			// 回滚存储文件
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			throw SmartException.of(StatusMsg.StatusMsg_135, e.getMessage());
		}
	}

	public SmartResult delProject(BaseSimpleFormBean<Integer> formBean) {
		Integer projectid = formBean.getReqdata();

		CrowdsourceProject project = new CrowdsourceProject().selectById(projectid);
		if (project == null) return smartResult(StatusMsg.StatusMsg_301);

		if (project.getState() != Constants.CROWDSOURCE_PROJECT_CREATE) {
			return smartResult(StatusMsg.StatusMsg_319);
		}
		// 删除项目的时候同时删除导入的文件
		if (project != null && project.getSourceFileId() != null) {
			projectFileService.delById(project.getSourceFileId());
		}
		if (project.deleteById()) {
			new CrowdsourceProjectItem().delete(Condition.create().eq("projectid", projectid));
			return smartResult();
		}
		return optFailSmartResult();
	}

	public SmartResult editProject(BaseSimpleFormBean<CrowdsourceEditFormBean> formBean){
		CrowdsourceEditFormBean reqdata = formBean.getReqdata();
		CrowdsourceProject project = new CrowdsourceProject().selectById(reqdata.getProjectid());
		Asserts.notNull(project, StatusMsg.StatusMsg_301);

		project.setPartyId(reqdata.getPartyId()).updateById();
		// 修改发票主体
		Invoice invoice = new Invoice().selectOne(Condition.create().eq("projectid", project.getProjectid()).eq("project_type", ProjectType.CROWDSOURCE));
		if (invoice != null) {
			invoice.setPartyId(reqdata.getPartyId()).updateById();
		}

		if (project.getWorkType() == Constants.WORK_TYPE_1) {
			List<CrowdsourceInvoice> invoiceList = new CrowdsourceInvoice().selectList(Condition.create().eq("projectid", project.getProjectid()));
			for (CrowdsourceInvoice crowdsourceInvoice : invoiceList) {
				crowdsourceInvoice.setPartyId(reqdata.getPartyId()).updateById();
			}
		}
		if (project.getWorkType() == Constants.WORK_TYPE_2) {
			List<ContractorInvoice> invoiceList = new ContractorInvoice().selectList(Condition.create().eq("projectid", project.getProjectid()));
			for (ContractorInvoice contractorInvoice : invoiceList) {
				contractorInvoice.setPartyId(reqdata.getPartyId()).updateById();
			}
		}
		return smartResult();
	}

	@Transactional
	public SmartResult submitAndPayProject(BaseSimpleFormBean<SubmitAndPayProjectFormBean> formBean) {
		SubmitAndPayProjectFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int projectid = reqdata.getProjectid();
		String phone = notificationConfig.getBossPhone();
		String verifyCode = reqdata.getVerifyCode();
		Integer actualSender = reqdata.getActualSender();
		Date applyInvoiceDate = reqdata.getApplyInvoiceDate();
		Integer asProtocol = reqdata.getAsProtocol();
		String companyInvoiceRemark = reqdata.getCompanyInvoiceRemark();

		if (asProtocol != null && asProtocol == 0 && applyInvoiceDate == null) {
			// 不按协议开票时, applyInvoiceDate必填
			return SmartResult.fail(StatusMsg.StatusMsg_645);
		} else if ((asProtocol == null || asProtocol == 1) && applyInvoiceDate != null) {
			// 按协议开票时, applyInvoiceDate不能填
			return SmartResult.fail(StatusMsg.StatusMsg_646);
		}

		//提交项目
		CrowdsourceProject project = crowdsourceProjectService.getAndRefreshProject(projectid);
		if (project == null) return smartResult(StatusMsg.StatusMsg_301);

		Company company = new Company().selectById(project.getCompid());
		Asserts.notNull(company,StatusMsg.StatusMsg_302);

		// 校验验证码
		commonService.checkPhoneVerifyCode(phone, verifyCode);
		// 支付前校验企业信息
		coreCompanyService.checkCompanyPayBeforeCroOrOdd(project.getCompid(), project.getWorkType());

		// 判断当前余额是否能够支付项目款
		BigDecimal projectAmountSum = project.getProjectTotalPayableAmount();
		SmartResult checkBalanceResult = coreProjectService.checkCompanyAccountForProject(project.getCompid(), project.getPayId(), projectAmountSum);
		if (checkBalanceResult.isFailed()) {
			throw new SmartException(StatusMsg.StatusMsg_372);
		}

		//提交项目
		return submitAndPayInternal(company, project, actualSender, applyInvoiceDate, asProtocol, companyInvoiceRemark);

	}

	private SmartResult submitAndPayInternal(Company company,CrowdsourceProject project, Integer actualSender,
											 Date applyInvoiceDate, Integer asProtocol, String companyInvoiceRemark) {
		project.setActualSender(actualSender)
			   .setApplyInvoiceDate(applyInvoiceDate)
			   .setAsProtocol(asProtocol);
		if (!project.updateById()) {
			return smartResult(StatusMsg.StatusMsg_333);
		}

		List<CrowdsourceProjectItemDto> itemList = crowdsourceProjectItemMapper.getItemList(project.getProjectid());
		if (itemList.size() > 500) {
			return smartResult(StatusMsg.StatusMsg_654);
		}

		// 支付方式
		Integer payId = project.getPayId();
		Payment payment = new Payment().selectById(project.getPayId());

		//智零工业务
		if (NumberUtil.equals(Constants.WORK_TYPE_2, project.getWorkType())) {
			//只能是线下支付或平安银行支付
			if(!NumberUtil.intIn(payId, CompanyPayType.PINGAN_TRANSFER_RANCHENG,CompanyPayType.PINGAN_CHENSHUANG,CompanyPayType.PLATFORM_OFFLINE)) {
				return smartResult(StatusMsg.StatusMsg_269);
			}
		}
		//检查项目金额必须大于0
		List<CrowdsourceProjectItemDto> zeroAmountList = itemList.stream()
																 .filter(item -> item.getProjectAmount() == null || item.getProjectAmount().compareTo(BigDecimal.ZERO) <= 0)
																 .collect(Collectors.toList());
		if (!CollectionUtils.isEmpty(zeroAmountList)) {
			return smartResult(StatusMsg.StatusMsg_609).setList(zeroAmountList);
		}
		// 众包项目不可以给自然人发单
		if (NumberUtil.equals(Constants.WORK_TYPE_1, project.getWorkType())) {
			List<CrowdsourceProjectItemDto> personalErrorList = itemList.stream()
																		.filter(item -> item.getUserType() == CrowdsourceUserType.NATURAL_PERSON)
																		.collect(Collectors.toList());
			if (!CollectionUtils.isEmpty(personalErrorList)) {
				return SmartResult.fail(StatusMsg.StatusMsg_640).setList(personalErrorList);
			}
		}

		// 判断创客是否注销, 已注销的不能发布
		List<CrowdsourceProjectItemDto> makerErrorList = new ArrayList<>();
		// 天津/芜湖创客还未开税户的,不能交易
		List<CrowdsourceProjectItemDto> unTaxAcctList = new ArrayList<>();
		// 创客申请注销已受理的，不能发布项目
		List<CrowdsourceProjectItemDto> rescissionList = new ArrayList<>();
		// 创客注册地和支付方式限制发众包项目，不能发布项目
		List<CrowdsourceProjectItemDto> forbidPublishList = new ArrayList<>();
		// 如果企业支付方式是支付宝 创客是否填写支付宝账号
		List<CrowdsourceProjectItemDto> aliMakerList = new ArrayList<>();

		List<Integer> passCitys = crowdsourcePayConfigMapper.selectCitysByPayType(payId);

		itemList.stream().forEach(item -> {
			if (item.getUserType() != CrowdsourceUserType.STUDIO) {
				return;
			}
			int userid = NumberUtil.safeInt(item.getUserid());
			MakerDetailDto userDetail = makerMapper.getUserState(userid);
			if (userDetail != null) {
				if(!NumberUtil.equals(userDetail.getState(), Constants.user_state_2)){
					makerErrorList.add(item);
				}
				// 天津/芜湖创客还未开税户的,不能交易
				if(NumberUtil.intIn(userDetail.getOpeningLocation(), 1,3) && !NumberUtil.equals(userDetail.getTaxAcctState(), 3)){
					unTaxAcctList.add(item);
				}
				//众包发单的时候增加判断如果是芜湖工作室必须是信圣支付方式才行
				if (!NumberUtil.intIn(userDetail.getOpeningLocation(), passCitys)) {
					forbidPublishList.add(item);
				}
				// 创客申请注销已受理的，不能发布项目
				if(NumberUtil.equals(userDetail.getRescissionState(), Constants.user_rescission_state_2)){
					rescissionList.add(item);
				}
				// 2022.12.30 增加如果企业支付方式是支付宝 判断创客是否填写支付宝账号
				if (PayTypeSn.ZFB.equals(payment.getPayTypeSn()) && StringUtil.isEmpty(userDetail.getAlipayAccount())) {
					aliMakerList.add(item);
				}
			}
		});
		if (!CollectionUtils.isEmpty(makerErrorList)) {
			return SmartResult.fail(StatusMsg.StatusMsg_231).setList(makerErrorList);
		}
		if (!CollectionUtils.isEmpty(unTaxAcctList)) {
			return SmartResult.fail(StatusMsg.StatusMsg_260).setList(unTaxAcctList);
		}
		if (!CollectionUtils.isEmpty(rescissionList)) {
			return SmartResult.fail(StatusMsg.StatusMsg_261).setList(rescissionList);
		}
		if (!CollectionUtils.isEmpty(forbidPublishList)) {
			return SmartResult.fail(StatusMsg.StatusMsg_268).setList(forbidPublishList);
		}
		if (!CollectionUtils.isEmpty(aliMakerList)) {
			return SmartResult.fail(StatusMsg.StatusMsg_485).setList(aliMakerList);
		}
		// 判断自然人是否上传了身份证正反面,没有上传不能发单
		List<CrowdsourceProjectItemDto> noIdPhotoList = itemList.stream().filter(item -> {
			if (item.getUserType() != CrowdsourceUserType.NATURAL_PERSON) return false;
			CrowdsourceFile idCardFrontFile = new CrowdsourceFile().selectOne(
					Condition.create().eq("crowdsourceid", item.getUserid()).eq("file_type", 1));
			CrowdsourceFile idCardBackFile = new CrowdsourceFile().selectOne(
					Condition.create().eq("crowdsourceid", item.getUserid()).eq("file_type", 2));
			if (idCardFrontFile == null || idCardBackFile == null) return true;
			return false;
		}).collect(Collectors.toList());

		//计算项目金额/税费返回数据集合
		Map<Integer,BigDecimal> calcTaxFeeMap = new HashMap<>();
		Map<Integer,BigDecimal> calcProjectAmountMap = new HashMap<>();

		//企业设置的城市的限额
		CrowdsourceCityQuota personalQuota = crowdsourceProjectService.findPersonalCityQuota(project.getCrowdsourceCity());

		// 2020.12.27, 阶梯费率,在提交项目时需要重新计算项目款税费.
		List<CrowdsourceItemAmountCalcResult> itemAmountCalcList = itemList.stream().map(item -> {
			CrowdsourceProjectItemModel itemCalc = new CrowdsourceProjectItemModel();
			itemCalc.setUserid(item.getUserid()).setUserType(item.getUserType()).setProjectAmount(item.getProjectAmount());
			CrowdsourceItemAmountCalcResult itemAmountCalc = null;

			BigDecimal lastTaxFee = BigDecimal.ZERO;
			BigDecimal lastProjectAmount = BigDecimal.ZERO;
			if (calcTaxFeeMap.get(item.getUserid()) != null) {
				lastTaxFee = calcTaxFeeMap.get(item.getUserid());
				lastProjectAmount = calcProjectAmountMap.get(item.getUserid());
			}
			itemAmountCalc = crowdsourceProjectService.calcItemAmountRepeat(project, itemCalc, company, CalcAmountType.PROCESSING, lastProjectAmount, lastTaxFee);
			calcTaxFeeMap.put(item.getUserid(), lastTaxFee.add(itemAmountCalc.getProjectServiceCharge()));
			calcProjectAmountMap.put(item.getUserid(), lastProjectAmount.add(itemAmountCalc.getProjectAmount()));

			// 创客工作室限额
			CrowdsourceCityQuota studioQuota = null;
			if (item.getUserType() == CrowdsourceUserType.STUDIO) {
				studioQuota = crowdsourceProjectService.findStudioCityQuota(item.getUserid());
			}
			// 计算各个限额
			crowdsourceProjectService.handleProjectItemCalcQuota(company, itemAmountCalc, personalQuota, studioQuota);
			// 更新最新计算的项目金额
			new CrowdsourceProjectItem().setId(item.getId())
										.setDepositAmount(itemAmountCalc.getDepositAmount())
										.setIntegratedTaxFee(itemAmountCalc.getIntegratedTaxFee())
										.setPartnerBrokerage(itemAmountCalc.getPartnerBrokerage())
										.setProjectServiceCharge(itemAmountCalc.getProjectServiceCharge())
										.setTaxRate(itemAmountCalc.getTaxRate())
										.updateById();
			item.setIntegratedTaxFee(itemAmountCalc.getIntegratedTaxFee())
				.setDepositAmount(itemAmountCalc.getDepositAmount())
				.setPartnerBrokerage(itemAmountCalc.getPartnerBrokerage())
				.setProjectServiceCharge(itemAmountCalc.getProjectServiceCharge())
				.setTaxRate(itemAmountCalc.getTaxRate());
			return itemAmountCalc;
		}).collect(Collectors.toList());

		// 重新计算项目款税费后， 更新项目合计
		crowdsourceProjectService.refreshProjectDetail(project);

		List<CrowdsourceItemAmountCalcResult> projectItemExceedList = LimitPromptUtil.checkExceedList(itemAmountCalcList);
		if (!CollectionUtils.isEmpty(projectItemExceedList)) {
			return smartResult(StatusMsg.StatusMsg_614).setList(projectItemExceedList);
		}

		// 重新计算项目款税费后， 更新项目合计
		crowdsourceProjectService.refreshProjectDetail(project);

		//判断企业账户余额不足
		CompanyPayment companyPayment = companyPaymentMapper.getCompanyPayment(project.getCompid(), project.getPayId());
		if (companyPayment.getBalance().compareTo(project.getProjectTotalPayableAmount()) < 0) {
			return smartResult(StatusMsg.StatusMsg_310);
		}

		// 准备项目合伙人佣金
		coreBrokerageService.prepareProjectBrokerage(project.getCompid(), 0, project.getProjectid(), ProjectType.CROWDSOURCE);

		//支付
		SmartResult result = crowdsourceProjectService.payCrowdsourceProject(project, companyInvoiceRemark);
		if (result.isSuccessful() && !CollectionUtils.isEmpty(noIdPhotoList)) {
			result.setList(noIdPhotoList);
		}
		return result;
	}

	public  void generalCroDeliveryProject(){
		List<String> projectIds = crowdsourceProjectMapper.getCompProjectDeliveryNumType2();
		if(!CollectionUtils.isEmpty(projectIds)){
			String ids = StringUtils.join(projectIds, ",");
			log.info("自动生成智众包智零工的代发单项目验收单开始,ID：" + ids);
			docService.generateCrowdsourceDocDeliverFile(0, ids, 3, true);
		}

	}
}
